Excel Export provides a way to export an Excel file with multiple sheets. This can be useful when you need to export data from different grids into a single Excel file.
How it works Copy Link
Exporting the grid into different sheets follows a specific process:
- You start the process by calling the
getSheetDataForExcelmethod on a grid instance to get the data exported for a specific sheet. - You call this method multiple times either on the same grid with different data (or different export params) or on different instances of the grid, and you store each exported data set as an element of an Array.
- Once all the needed sheets have been stored in the Array, call the
exportMultipleSheetsAsExcelorgetMultipleSheetsAsExcelmethods to package them in a single Excel workbook.
Calling getSheetDataForExcel starts a Multiple Sheet export process, that can only be ended by calling the exportMultipleSheetsAsExcel or getMultipleSheetsAsExcel methods. Until one of these two methods is called to complete the process, no data can be exported from the grid using exportDataAsExcel or getDataAsExcel.
Using Selected Rows Copy Link
In this example, we use the onlySelected=true property to segment the grid data into multiple sheets, each containing 100 data rows. Specifically:
- We manually select 100 rows at a time using
setNodesSelected. - We then use
getSheetDataForExcelwith theonlySelectedoption to generate sheet data for these selected nodes only. - We then deselect rows again to avoid affecting the UI.
Note the following:
- The header is exported on each page, so each page will contain 101 records (including the header).
- Because each export did not have a specified
sheetName, they will be namedag-grid,ag-grid_1,ag-grid_2and so on.
import {
ClientSideRowModelModule,
ColDef,
GridApi,
GridOptions,
IRowNode,
ModuleRegistry,
NumberFilterModule,
RowApiModule,
RowSelectionModule,
TextFilterModule,
createGrid,
enableDevValidations,
} from "ag-grid-community";
import {
ColumnMenuModule,
ContextMenuModule,
ExcelExportModule,
} from "ag-grid-enterprise";
import { IOlympicData } from "./interfaces";
// Enable extended validations only for development
if (process.env.NODE_ENV !== "production") {
enableDevValidations();
}
ModuleRegistry.registerModules([
TextFilterModule,
NumberFilterModule,
RowSelectionModule,
RowApiModule,
ClientSideRowModelModule,
ExcelExportModule,
ColumnMenuModule,
ContextMenuModule,
]);
const columnDefs: ColDef[] = [
{ field: "athlete", minWidth: 200 },
{ field: "age" },
{ field: "country", minWidth: 200 },
{ field: "year" },
{ field: "date", minWidth: 150 },
{ field: "sport", minWidth: 150 },
{ field: "gold" },
{ field: "silver" },
];
let gridApi: GridApi<IOlympicData>;
const gridOptions: GridOptions<IOlympicData> = {
defaultColDef: {
filter: true,
minWidth: 100,
flex: 1,
},
columnDefs,
rowSelection: {
mode: "multiRow",
checkboxes: false,
headerCheckbox: false,
},
};
function onBtExport() {
const spreadsheets: string[] = [];
let nodesToExport: IRowNode[] = [];
gridApi!.forEachNode((node, index) => {
nodesToExport.push(node);
if (index % 100 === 99) {
gridApi!.setNodesSelected({ nodes: nodesToExport, newValue: true });
spreadsheets.push(
gridApi!.getSheetDataForExcel({
onlySelected: true,
})!,
);
gridApi!.deselectAll();
nodesToExport = [];
}
});
// check if the last page was exported
if (gridApi!.getSelectedNodes().length) {
spreadsheets.push(
gridApi!.getSheetDataForExcel({
onlySelected: true,
})!,
);
gridApi!.deselectAll();
}
gridApi!.exportMultipleSheetsAsExcel({
data: spreadsheets,
fileName: "ag-grid.xlsx",
});
}
const gridDiv = document.querySelector<HTMLElement>("#myGrid")!;
gridApi = createGrid(gridDiv, gridOptions);
fetch("https://www.ag-grid.com/example-assets/olympic-winners.json")
.then((response) => response.json())
.then((data: IOlympicData[]) => gridApi!.setGridOption("rowData", data));
if (typeof window !== "undefined") {
// Attach external event handlers to window so they can be called from index.html
(<any>window).onBtExport = onBtExport;
}
.grid-wrapper {
display: flex;
flex: 1 1 0px;
flex-grow: 1;
}
.grid-wrapper > div {
width: 100%;
height: 100%;
}
.container {
display: flex;
flex-direction: column;
height: 100%;
}
.columns {
display: flex;
flex-direction: row;
gap: 16px;
}
<div class="container">
<div>
<button onclick="onBtExport()" style="margin-bottom: 5px; font-weight: bold">Export to Excel</button>
</div>
<div class="grid-wrapper">
<div id="myGrid"></div>
</div>
</div>
export interface IOlympicData {
athlete: string,
age: number,
country: string,
year: number,
date: string,
sport: string,
gold: number,
silver: number,
bronze: number,
total: number
} Using Data Filtering Copy Link
In this example, we filter on the sport column to segment the grid data into multiple sheets, each containing all the data for a specific sport value.
Note the following:
- The exported Excel file will contain one sheet for each sport result.
- Each sheet was exported using the sport name as the name of the sheet.
import {
ClientSideRowModelModule,
ColDef,
GridApi,
GridOptions,
ModuleRegistry,
NumberFilterModule,
RowApiModule,
createGrid,
enableDevValidations,
} from "ag-grid-community";
import {
ColumnMenuModule,
ContextMenuModule,
ExcelExportModule,
SetFilterModule,
} from "ag-grid-enterprise";
import { IOlympicData } from "./interfaces";
// Enable extended validations only for development
if (process.env.NODE_ENV !== "production") {
enableDevValidations();
}
ModuleRegistry.registerModules([
NumberFilterModule,
RowApiModule,
ClientSideRowModelModule,
ExcelExportModule,
ColumnMenuModule,
ContextMenuModule,
SetFilterModule,
]);
const columnDefs: ColDef[] = [
{ field: "athlete", minWidth: 200 },
{ field: "age" },
{ field: "country", minWidth: 200 },
{ field: "year" },
{ field: "date", minWidth: 150 },
{ field: "sport", minWidth: 150 },
{ field: "gold" },
{ field: "silver" },
];
let gridApi: GridApi<IOlympicData>;
const gridOptions: GridOptions<IOlympicData> = {
defaultColDef: {
filter: true,
minWidth: 100,
flex: 1,
},
columnDefs: columnDefs,
};
function onBtExport() {
const sports: Record<string, boolean> = {};
gridApi!.forEachNode(function (node) {
if (!sports[node.data!.sport]) {
sports[node.data!.sport] = true;
}
});
let spreadsheets: string[] = [];
const performExport = async () => {
for (const sport in sports) {
await gridApi!.setColumnFilterModel("sport", { values: [sport] });
gridApi!.onFilterChanged();
if (gridApi!.getColumnFilterModel("sport") == null) {
throw new Error("Example error: Filter not applied");
}
const sheet = gridApi!.getSheetDataForExcel({
sheetName: sport,
});
if (sheet) {
spreadsheets.push(sheet);
}
}
await gridApi!.setColumnFilterModel("sport", null);
gridApi!.onFilterChanged();
gridApi!.exportMultipleSheetsAsExcel({
data: spreadsheets,
fileName: "ag-grid.xlsx",
});
spreadsheets = [];
};
performExport();
}
const gridDiv = document.querySelector<HTMLElement>("#myGrid")!;
gridApi = createGrid(gridDiv, gridOptions);
fetch("https://www.ag-grid.com/example-assets/olympic-winners.json")
.then((response) => response.json())
.then((data: IOlympicData[]) => gridApi!.setGridOption("rowData", data));
if (typeof window !== "undefined") {
// Attach external event handlers to window so they can be called from index.html
(<any>window).onBtExport = onBtExport;
}
.grid-wrapper {
display: flex;
flex: 1 1 0px;
flex-grow: 1;
}
.grid-wrapper > div {
width: 100%;
height: 100%;
}
.container {
display: flex;
flex-direction: column;
height: 100%;
}
.columns {
display: flex;
flex-direction: row;
gap: 16px;
}
<div class="container">
<div>
<button onclick="onBtExport()" style="margin-bottom: 5px; font-weight: bold">Export to Excel</button>
</div>
<div class="grid-wrapper">
<div id="myGrid"></div>
</div>
</div>
export interface IOlympicData {
athlete: string,
age: number,
country: string,
year: number,
date: string,
sport: string,
gold: number,
silver: number,
bronze: number,
total: number
} Multiple Grids to Multiple Sheets Copy Link
In this example, we export two grids, each into a separate sheet of the same Excel file. Drag a few rows from the grid on the left into the grid on the right and click the export button above the grid.
Note the following:
- The contents of the
Athletesgrid will be exported to theAthletessheet. - The contents of the
Selected Athletesgrid will be exported to theSelected Athletessheet. - Only the
onExcelExportmethod is relevant to Excel Export
import {
ClientSideRowModelApiModule,
ClientSideRowModelModule,
ColDef,
GetRowIdParams,
GridApi,
GridOptions,
GridReadyEvent,
ICellRendererComp,
ICellRendererParams,
ModuleRegistry,
RowDragModule,
RowSelectionModule,
TextFilterModule,
createGrid,
enableDevValidations,
} from "ag-grid-community";
import {
ColumnMenuModule,
ContextMenuModule,
ExcelExportModule,
} from "ag-grid-enterprise";
// Enable extended validations only for development
if (process.env.NODE_ENV !== "production") {
enableDevValidations();
}
ModuleRegistry.registerModules([
ClientSideRowModelApiModule,
TextFilterModule,
RowDragModule,
RowSelectionModule,
ClientSideRowModelModule,
ColumnMenuModule,
ContextMenuModule,
ExcelExportModule,
]);
class SportRenderer implements ICellRendererComp {
eGui!: HTMLElement;
init(params: ICellRendererParams) {
this.eGui = document.createElement("i");
this.eGui.addEventListener("click", () => {
params.api.applyTransaction({ remove: [params.node.data] });
});
this.eGui.classList.add("far", "fa-trash-alt");
this.eGui.style.cursor = "pointer";
}
getGui() {
return this.eGui;
}
refresh(params: ICellRendererParams): boolean {
return false;
}
}
const leftColumnDefs: ColDef[] = [
{
rowDrag: true,
maxWidth: 50,
suppressHeaderMenuButton: true,
suppressHeaderFilterButton: true,
rowDragText: (params, dragItemCount) => {
if (dragItemCount > 1) {
return dragItemCount + " athletes";
}
return params.rowNode!.data.athlete;
},
},
{ field: "athlete" },
{ field: "sport" },
];
const rightColumnDefs: ColDef[] = [
{
rowDrag: true,
maxWidth: 50,
suppressHeaderMenuButton: true,
suppressHeaderFilterButton: true,
rowDragText: (params, dragItemCount) => {
if (dragItemCount > 1) {
return dragItemCount + " athletes";
}
return params.rowNode!.data.athlete;
},
},
{ field: "athlete" },
{ field: "sport" },
{
suppressHeaderMenuButton: true,
suppressHeaderFilterButton: true,
maxWidth: 50,
cellRenderer: SportRenderer,
},
];
let leftApi: GridApi;
const leftGridOptions: GridOptions = {
defaultColDef: {
flex: 1,
minWidth: 100,
filter: true,
},
rowSelection: { mode: "multiRow" },
rowDragMultiRow: true,
getRowId: (params: GetRowIdParams) => {
return params.data.athlete;
},
rowDragManaged: true,
suppressMoveWhenRowDragging: true,
columnDefs: leftColumnDefs,
onGridReady: (params) => {
addGridDropZone(params);
},
};
let rightApi: GridApi;
const rightGridOptions: GridOptions = {
defaultColDef: {
flex: 1,
minWidth: 100,
filter: true,
},
getRowId: (params: GetRowIdParams) => {
return params.data.athlete;
},
rowDragManaged: true,
columnDefs: rightColumnDefs,
};
function addGridDropZone(params: GridReadyEvent) {
const dropZoneParams = rightApi!.getRowDropZoneParams({
onDragStop: (params) => {
const nodes = params.nodes;
leftApi!.applyTransaction({
remove: nodes.map(function (node) {
return node.data;
}),
});
},
});
params.api.addRowDropZone(dropZoneParams);
}
function loadGrid(
options: GridOptions,
oldApi: GridApi,
side: string,
data: any[],
) {
const grid = document.querySelector<HTMLElement>("#e" + side + "Grid")!;
oldApi?.destroy();
options.rowData = data;
return createGrid(grid, options);
}
function loadGrids() {
fetch("https://www.ag-grid.com/example-assets/olympic-winners.json")
.then((response) => response.json())
.then(function (data) {
const athletes: any[] = [];
let i = 0;
while (athletes.length < 20 && i < data.length) {
const pos = i++;
if (
athletes.some(function (rec) {
return rec.athlete === data[pos].athlete;
})
) {
continue;
}
athletes.push(data[pos]);
}
leftApi = loadGrid(
leftGridOptions,
leftApi,
"Left",
athletes.slice(0, athletes.length / 2),
);
rightApi = loadGrid(
rightGridOptions,
rightApi,
"Right",
athletes.slice(athletes.length / 2),
);
});
}
function onExcelExport() {
const spreadsheets = [];
spreadsheets.push(
leftApi!.getSheetDataForExcel({ sheetName: "Athletes" })!,
rightApi!.getSheetDataForExcel({ sheetName: "Selected Athletes" })!,
);
// could be leftGridOptions or rightGridOptions
leftApi!.exportMultipleSheetsAsExcel({
data: spreadsheets,
fileName: "ag-grid.xlsx",
});
}
const resetBtn = document.querySelector("button.reset")!;
const exportBtn = document.querySelector("button.excel")!;
resetBtn.addEventListener("click", () => {
loadGrids();
});
exportBtn.addEventListener("click", () => {
onExcelExport();
});
loadGrids();
.top-container {
height: 100%;
display: flex;
flex-direction: column;
}
.panel-body > input:not(:first-of-type) {
margin-left: 10px;
}
.grid-wrapper {
display: flex;
flex: 1 1 auto;
margin-top: 5px;
}
.grid-wrapper .panel {
flex: 1 1 50%;
display: flex;
flex-direction: column;
overflow: hidden;
}
.grid-wrapper .panel-body {
flex: 1 1 auto;
overflow: hidden;
padding: 0;
display: flex;
}
.grid-wrapper .panel-body > div {
width: 100%;
}
<div class="top-container">
<div>
<button type="button" class="btn btn-default excel">
<i class="far fa-file-excel" style="margin-right: 5px; color: green"></i>Export to Excel
</button>
<button type="button" class="btn btn-default reset">
<i class="fas fa-redo" style="margin-right: 5px"></i>Reset
</button>
</div>
<div class="grid-wrapper">
<div class="panel panel-primary" style="margin-right: 10px">
<div class="panel-heading">Athletes</div>
<div class="panel-body">
<div id="eLeftGrid"></div>
</div>
</div>
<div class="panel panel-primary" style="margin-left: 10px">
<div class="panel-heading">Selected Athletes</div>
<div class="panel-body">
<div id="eRightGrid"></div>
</div>
</div>
</div>
</div>
API Copy Link
API Methods Copy Link
This is method to be used to get the grid's data as a sheet, that will later be exported either by getMultipleSheetsAsExcel() or exportMultipleSheetsAsExcel(). |
Downloads an Excel export of multiple sheets in one file. |
Similar to exportMultipleSheetsAsExcel, except instead of downloading a file, it will return a Blob to be processed by the user. |