Angular Exportación de cuadrícula al servicio de Excel

    The Excel Exporter service can export data to excel from the IgxGrid. The data export functionality is encapsulated in the IgxExcelExporterService class and the data is exported in MS Excel table format. This format allows features like filtering, sorting, etc. To do this you need to invoke the IgxExcelExporterService's export method and pass the IgxGrid component as first argument to export grid easily.

    Angular Excel Exporter Example

    Exporting Grid's Data

    To start using the IgniteUI Excel Exporter first import the IgxExcelExporterService in the app.module.ts file and add the service to the providers array:

    // app.module.ts
    import { IgxExcelExporterService } from 'igniteui-angular';
    // import { IgxExcelExporterService } from '@infragistics/igniteui-angular'; for licensed package
    
    @NgModule({
      providers: [ IgxExcelExporterService ]
    })
    
    export class AppModule {}
    
    Note

    En v12.2.1 y posteriores, los servicios de exportación se brindan en la raíz, lo que significa que ya no es necesario declararlos en los proveedores de AppModule.

    Para iniciar un proceso de exportación, puede utilizar el controlador de un botón en la plantilla de su componente.

    <igx-grid #grid [data]="localData" [autoGenerate]="true"></igx-grid>
    <button (click)="exportButtonHandler()">Export IgxGrid to Excel</button>
    

    You may access the exporter service by defining an argument of type IgxExcelExporterService in the component's constructor and the Angular framework will provide an instance of the service. To export some data in MS Excel format you need to invoke the exporter service's export method and pass the IgxGrid component as first argument.

    Aquí está el código que ejecutará el proceso de exportación en el archivo mecanografiado del componente:

    // component.ts
    import { IgxExcelExporterService, IgxExcelExporterOptions } from 'igniteui-angular';
    import { IgxGridComponent } from 'igniteui-angular';
    
    @ViewChild('grid') public grid: IgxGridComponent;
    
    constructor(private excelExportService: IgxExcelExporterService) {
    }
    
    public exportButtonHandler() {
      this.excelExportService.export(this.grid, new IgxExcelExporterOptions('ExportedDataFile'));
    }
    

    Si todo salió bien, deberías ver el componente IgxGrid y un botón debajo de él. Al presionar el botón, se activará el proceso de exportación y el navegador descargará un archivo llamado "ExportedDataFile.xlsx" que contiene los datos del componente Grid en formato MS Excel.

    Export All Data

    Hay algunos casos en los que es posible que esté utilizando operaciones remotas como paginación y Grid no tendrá acceso a todos sus datos. En estos casos, recomendamos utilizar el Servicio de exportación de Excel y pasar toda la recopilación de datos, si está disponible. Ejemplo:

    public exportButtonHandler() {
      this.excelExportService.exportData(this.localData, new IgxExcelExporterOptions('ExportedDataFile'));
    }
    

    Export Grouped Data

    Para exportar datos agrupados solo necesita agrupar el Grid por una o más columnas. El navegador descargará un archivo llamado "ExportedDataFile.xlsx" que contiene los datos del componente Grid en formato MS Excel agrupados por la columna seleccionada. Ejemplo:

    Export Multi Column Headers Grid

    It is now possible to export Grid with defined multi-column headers. All headers will be reflected in the exported excel file as they are displayed in the Grid. If you want to exclude the defined multi-column headers from the exported data you can set the exporter option ignoreMultiColumnHeaders to true.

    Note

    La cuadrícula exportada no tendrá formato de tabla, ya que las tablas de Excel no admiten encabezados de filas múltiples.

    Export Grid with Frozen Column Headers

    By default Excel Exporter service exports the grid with scrollable (unfrozen) column headers. There are scenarios in which you may want to freeze all headers on top of the exported excel file so they always stay in view as the user scrolls through the records. To achieve this you could set the exporter option freezeHeaders to true.

    public exportButtonHandler() {
        const exporterOptions = new IgxExcelExporterOptions('ExportedDataFile');
        exporterOptions.freezeHeaders = true;
        this.excelExportService.export(this.grid, exporterOptions);
    }
    

    Customizing the Exported Content

    In the above examples the Excel Exporter service was exporting all available data. There are situations in which you may want to skip exporting a row or even an entire column. To achieve this you may hook to the columnExporting and/or rowExporting events which are fired respectively for each column and/or each row and cancel the respective event by setting the event argument object's cancel property to true.

    El siguiente ejemplo excluirá una columna de la exportación si su encabezado es "Edad" y si su índice es 1:

    // component.ts
    
    this.excelExportService.columnExporting.subscribe((args: IColumnExportingEventArgs) => {
      if (args.header == 'Age' && args.columnIndex == 1) {
          args.cancel = true;
      }
    });
    this.excelExportService.export(this.grid, new IgxExcelExporterOptions('ExportedDataFile'));
    

    When you are exporting data from the Grid component, the export process takes in account features like row filtering and column hiding and exports only the data visible in the Grid. You can configure the exporter service to include filtered rows or hidden columns by setting properties on the IgxExcelExporterOptions object.

    Known Limitations

    Limitación Descripción
    Tamaño máximo de hoja de trabajo El tamaño máximo de hoja de cálculo admitido por Excel es 1.048.576 filas por 16.384 columnas.
    Estilo celular El servicio de exportación de Excel no admite la exportación de un estilo personalizado aplicado a un componente de celda. En tales escenarios, recomendamos utilizar la Biblioteca de Excel.

    API References

    El servicio Excel Exporter tiene algunas API más para explorar, que se enumeran a continuación.

    Componentes adicionales que se utilizaron:

    Additional Resources

    Nuestra comunidad es activa y siempre da la bienvenida a nuevas ideas.