Search code examples
javascripttypescriptag-grid

AgGrid Excel Export Stripping Leading 0's


I am trying to export a grid to Excel. Values in the model cells are not exported correctly. Instead of exporting as

0001458
0008451
0008451

They display as:

1458
8451
8451

The actual values coming from the API returning the data for model is coming as string, so:

'0001458'
'0008451'
'0008451'

Example: https://stackblitz.com/edit/ag-grid-react-hello-world-r3sjfn?file=index.js

import React, { useState, useEffect, useRef } from 'react';
import { render } from 'react-dom';
import { AgGridReact } from 'ag-grid-react';

import 'ag-grid-community/styles/ag-grid.css';
import 'ag-grid-community/styles/ag-theme-alpine.css';

const myPromise = new Promise((resolve, reject) => {
  setTimeout(() => {
    resolve(
      [
        { make: 'Toyota', model: '0001458', price: 35000 },
        { make: 'Ford', model: '0008451', price: 32000 },
        { make: 'Porsche', model: '0085452', price: 72000 },
      ]
    );
  }, 300);
});

 
const App = () => {
  const [rowData, setRowData] = useState([]);
  const initData = useRef([]);
  const gridApi = useRef();

  const [columnDefs] = useState([
    { field: 'make' },
    { field: 'model' },
    { field: 'price', editable: true },
  ]);

  const gridReady = (params) => {
    gridApi.current = params?.api;
  }

  useEffect(() => {
    let data = myPromise
      .then((data) => {
        console.log(data);
        setRowData(data);
        initData.current = JSON.parse(JSON.stringify(data));
      });
  }, []);

  const exportExcel = () => {
    gridApi.current.exportDataAsExcel();
  }

  return (
    <div>
      <button onClick={exportExcel}>Back to original</button>

      <br></br>

      <div className="ag-theme-alpine" style={{ height: 400, width: 600 }}>
        <AgGridReact rowData={rowData} columnDefs={columnDefs} onGridReady={gridReady}></AgGridReact>
      </div>

    </div>
  );
};

Solution

  • The answer is https://www.ag-grid.com/react-data-grid/excel-export-data-types/

    This is how you can implement Thomas Renger's comment

    Define your types

    const excelStyles = useMemo(() => [
      {
        id: 'stringType',
        dataType: 'String',
      },
      // ...
    ]);
    

    Pass as a prop

    <AgGridReact
      ref={gridRef}
      rowData={rowData}
      excelStyles={excelStyles}
    />
    

    Define a value getter method (Important)

    const valueGetter = (params) => {
      return params.data.model;
    };
    

    Modify your column definitions like that

    const [columnDefs, setColumnDefs] = useState([
      { field: 'make' },
      {
        field: 'model',
        valueGetter: valueGetter,
        field: 'Model (String)',
        cellClass: 'stringType',
      },
      { field: 'price', editable: true },
    ]);
    

    Result Result

    Plunker: https://plnkr.co/edit/BK0WN7mLOcm0kzpk?preview