Reputation: 97
I am trying to create and export an Excel spreadsheet.
This is my code:
import XLSX from 'xlsx';
const downloadExcel = () => {
console.log(XLSX);
const worksheet = XLSX.utils.json_to_sheet(excelExport);
const workbook = XLSX.utils.book_new();
XLSX.utils.book_append_sheet(workbook, worksheet, 'kelvin');
//buffer
let buf = XLSX.write(workbook, { booktype: 'xlsx', type: 'buffer' });
//binary string
XLSX.write(workbook, { booktype: 'xlsx', type: 'binary' });
//download
XLSX.writeFile(workbook, 'kelvin.xlsx');
};
When trying to use this function, I get the following error:
Kelvin.js:64 Uncaught TypeError: Cannot read properties of undefined (reading 'utils')
. Additionally, when outputting the XLSX variable to the console, it says that it is undefined.
How am I supposed to import the contents of the 'xlsx' package?
Upvotes: 2
Views: 9039
Reputation: 131
I had the same error. In order to resolve it,
I changed the import line from: import XLSX from 'xlsx';
to this: import * as XLSX from 'xlsx';
based on this comment from the repo maintainer: https://github.com/SheetJS/sheetjs/issues/393#issuecomment-1300947901
and the project documentation: https://docs.sheetjs.com/docs/getting-started/installation/frameworks#usage
The fundamental issue is that, in SheetJS's transition from CJS to ESM modules, the way that bundlers would expose the exports changed resulting in needing to change the import method as outlined above.
Upvotes: 13
Reputation: 1
I had the same error with a Vuejs project.
My workaround was to go back to version 0.18.0 of xlsx (latest version right now is 0.18.5)
"xlsx": "^0.18.0"
Upvotes: 0