Search code examples
reactjsxlsx

I export my data to Excel but i get this error: Cannot read properties of undefined (reading 'editing')


I Want to export my material table data to Excel but when I click to download I get error in console: Cannot read properties of undefined (reading 'editing')

(I use "xlsx": "^0.18.0")

<div onClick={downloadExcel} className="downloadExcel">
      <img src="/assets/excel-svgrepo-com.svg" />
</div>

and my downloadExcel function is:

  const downloadExcel = () => {
    const newData = Apiary.map((row) => {
      delete row.tableData;
      return row;
    });
    const workSheet = XLSX.utils.json_to_sheet(newData);
    const workBook = XLSX.utils.book_new();
    XLSX.utils.book_append_sheet(workBook, workSheet, "students");
    //Buffer
    let buf = XLSX.write(workBook, { bookType: "xlsx", type: "buffer" });
    //Binary string
    XLSX.write(workBook, { bookType: "xlsx", type: "binary" });
    //Download
    XLSX.writeFile(workBook, "لیست زنبورستان.xlsx");
  };

when I onClick img my react is freeze and stop How can I fix this error?


Solution

  • TL;DR: Make sure you import the XLSX library like this: import * as XLSX from 'xlsx'


    I had a similar issue with the XLSX on Vue.js.

    I was importing the lib on a component with import XLSX from 'xlsx' and getting this error on the console:

    [Vue warn]: Error in v-on handler: "TypeError: Cannot read properties of undefined (reading 'utils')"
    

    And then I noticed on the terminal (which was running the vue.js app) the message: "export 'default' (imported as 'XLSX') was not found in 'xlsx'

    So I've resolved it by changing the import to: import * as XLSX from 'xlsx'