📜  angular 11 export excel with custom header - Javascript (1)

📅  最后修改于: 2023-12-03 14:59:17.733000             🧑  作者: Mango

Angular 11 Export Excel with Custom Header - Javascript

In this tutorial, we'll explore how to export data to an excel file in Angular 11 with a custom header. Exporting data to excel is a common requirement in many web applications, and knowing how to do it efficiently can be a valuable skill for any Angular developer.

Prerequisites

To follow along with this tutorial, you will need the following:

  • Basic knowledge of Angular
  • Node.js and npm installed on your machine
  • Angular CLI installed globally
Steps
  1. Create a new Angular project using the following command:

    ng new angular-export-excel --routing=false --style=scss
    
  2. Install the necessary packages for excel export:

    npm install file-saver xlsx @types/file-saver @types/xlsx --save
    

    Here we are installing file-saver, xlsx, and their corresponding type definitions.

  3. Create a new service that will handle our excel export logic. Use the following command to create a new service:

    ng g service services/excel-export
    
  4. Open the excel-export.service.ts file and add the following code:

    import { Injectable } from '@angular/core';
    import * as XLSX from 'xlsx';
    import * as FileSaver from 'file-saver';
    
    @Injectable({
      providedIn: 'root'
    })
    export class ExcelExportService {
    
      exportToExcel(selection: string[], data: any[], fileName: string, header: string[]) {
        const worksheet: XLSX.WorkSheet = XLSX.utils.json_to_sheet(data, { header: selection });
        const workbook: XLSX.WorkBook = {
          Sheets: { data: worksheet },
          SheetNames: ['data']
        };
        const excelBuffer: any = XLSX.write(workbook, { bookType: 'xlsx', type: 'array' });
        const blob = new Blob([excelBuffer], { type: 'application/octet-stream' });
        FileSaver.saveAs(blob, `${fileName}.xlsx`);
      }
    
    }
    
  5. In this code block, the exportToExcel() method handles the export logic. It takes four parameters:

    • selection - an array of strings that represents the column headers that we want to include in the exported file.
    • data - the data that we want to export.
    • fileName - the name to assign to the exported file.
    • header - an array of strings that represents the custom header that we want to display in the exported file.

    The method converts the data to a worksheet using json_to_sheet(), creates a workbook and assigns the worksheet to it, and then uses the write() method to write the workbook to an excel buffer. Finally, it creates a Blob and saves it using the FileSaver.saveAs() method.

  6. Open the app.module.ts file and import the ExcelExportService:

    import { ExcelExportService } from './services/excel-export.service';
    
  7. Add the ExcelExportService to the providers array:

    @NgModule({
      declarations: [
        AppComponent
      ],
      imports: [
        BrowserModule
      ],
      providers: [ExcelExportService],
      bootstrap: [AppComponent]
    })
    export class AppModule { }
    
  8. Open the component where you want to use the ExcelExportService. In this example, we'll add it to the AppComponent.

  9. Import the ExcelExportService:

    import { Component } from '@angular/core';
    import { ExcelExportService } from './services/excel-export.service';
    
  10. Create a mock data variable to represent the data that we want to export:

    data = [
      { name: 'John', age: 30, jobTitle: 'CEO' },
      { name: 'Jane', age: 25, jobTitle: 'CTO' },
      { name: 'Jim', age: 40, jobTitle: 'CFO' },
      { name: 'Kate', age: 35, jobTitle: 'COO' }
    ];
    
  11. Create a method to export the data to an excel file:

    exportToExcel() {
      const selection = ['name', 'age', 'jobTitle'];
      const fileName = 'Employee List';
      const header = ['Employee Name', 'Age', 'Job Title'];
      this.excelService.exportToExcel(selection, this.data, fileName, header);
    }
    

    Here we are passing the selection, data, fileName, and header variables to the exportToExcel() method.

  12. Finally, add a button to the HTML template to trigger the export method:

    <button (click)="exportToExcel()">Export to Excel</button>
    

    When the button is clicked, it calls the exportToExcel() method, which exports the data to an excel file.

Conclusion

In this tutorial, we learned how to export data to an excel file with a custom header in Angular 11. We used the xlsx and file-saver packages to handle the export logic and created a service to encapsulate the export logic. By following these steps, you can easily add excel export functionality to your Angular applications.