Reputation: 167
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?
Upvotes: 3
Views: 13141
Reputation: 21
Problem seems to be because of xlsx version. There are some breaking changes between 0.18.0 and 0.15.1. I was able to solve the issue in three ways:
import * as XLSX from 'xlsx/xlsx.js;
Actually, in newer version of xlsx, there are two files available, i.e, xlsx/xlsx.js and xlsx/xlsx.mjs. By default, app tries to load .mjs file while .mjs files are not importable by default.
By explicitly defining config to allow import of .mjs files in the app.
By using lower version of xlsx across whole project. xlsx version 0.15.1 will work.
Upvotes: 2
Reputation: 429
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'
Upvotes: 10