Excel/XLSX 库 SheetJS 导入后未定义

问题描述 投票:0回答:2

我正在尝试创建并导出 Excel 电子表格。

这是我的代码:

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');
  };

尝试使用此功能时,出现以下错误:

Kelvin.js:64 Uncaught TypeError: Cannot read properties of undefined (reading 'utils')
。另外,当将XLSX变量输出到控制台时,它说它是未定义的。

我该如何导入“xlsx”包的内容?

reactjs xlsx sheetjs
2个回答
10
投票

我也有同样的错误。为了解决这个问题,

我将导入行更改为:

import XLSX from 'xlsx';

对此:

import * as XLSX from 'xlsx';

基于回购维护者的评论:https://github.com/SheetJS/sheetjs/issues/393#issuecomment-1300947901

以及项目文档:https://docs.sheetjs.com/docs/getting-started/installation/frameworks#usage

根本问题是,在 SheetJS 从 CJS 到 ESM 模块的过渡中,捆绑器公开导出的方式发生了变化,导致需要更改如上所述的导入方法。


0
投票

我在 Vuejs 项目中遇到了同样的错误。

我的解决方法是回到 xlsx 0.18.0 版本(现在最新版本是 0.18.5)

"xlsx": "^0.18.0"
© www.soinside.com 2019 - 2024. All rights reserved.