Search code examples
jsonangularexport-to-excelag-gridag-grid-ng2

Export JSON to excel (csv) using Ag-grid


I want to export the json data to excel using Ag-grid. I want to keep the Ag-grid hidden(not-visible on UI) and just have the hyper link on UI to download the data in excel format.

Column Definition:

 this.columnDefs = [
        {headerName: "Athlete", field: "athlete", width: 150},
        {headerName: "Age", field: "age", width: 90},
        {headerName: "Country", field: "country", width: 120},
        {headerName: "Year", field: "year", width: 90},
        {headerName: "Date", field: "date", width: 110},
        {headerName: "Sport", field: "sport", width: 110},
        {headerName: "Gold", field: "gold", width: 100},
        {headerName: "Silver", field: "silver", width: 100},
        {headerName: "Bronze", field: "bronze", width: 100},
        {headerName: "Total", field: "total", width: 100}
    ];

Data:

[{"athlete":"Michael Phelps","age":23,"country":"United States","year":2008,"date":"24/08/2008","sport":"Swimming","gold":8,"silver":0,"bronze":0,"total":8},{"athlete":"Michael Phelps","age":23,"country":"United States","year":2008,"date":"24/08/2008","sport":"Swimming","gold":8,"silver":0,"bronze":0,"total":8},]

Here is the plunker link with code.


Solution

  • Exporting to Excel is an enterprise feature. However, in absence of an enterprise license, you should be able to call the gridOptions API to export the data to a .csv, which can be opened in Excel.

    The grid can be hidden using the [hidden] directive.

    Adapted from the ag-Grid API:

    <button (click)="onBtnExport()">Download</button>
    
    <ag-grid-angular
          #agGrid
          style="width: 100%; height: 100%;"
          id="myGrid"
          class="ag-theme-balham"
          [hidden]="true"
          [columnDefs]="columnDefs"
          [enableFilter]="true"
          [enableSorting]="true"
          [showToolPanel]="true"
          [rowSelection]="rowSelection"
          [pinnedTopRowData]="pinnedTopRowData"
          [pinnedBottomRowData]="pinnedBottomRowData"
          (gridReady)="onGridReady($event)"></ag-grid-angular>
    
    onBtnExport(): void {
        const params = {
          columnGroups: true,
          allColumns: true,
          fileName: 'filename_of_your_choice',
          columnSeparator: document.querySelector("#columnSeparator").value
        };
        this.gridApi.exportDataAsCsv(params);
    }