使用 SHEETJS 将 Excel 数据转换为 JSON

Converting Excel Data to JSON using SHEETJS

我正在尝试使用 SHEETJS 将我的 excel 文件转换为 JSON,但它显示 fs.readFileSync 不是一个函数。

import XLSX from 'xlsx';

function App() {

  const wb = XLSX.readFile("cricket.xlsx");
  const wsname = wb.SheetNames[0];
  const ws = wb.Sheets[wsname];
  const data = XLSX.utils.sheet_to_json(ws);
  console.log(data);

  return (
    <div className="App">
    </div>
  );
}

export default App;

https://github.com/SheetJS/sheetjs/issues/418

这个 github 问题似乎讨论了关于这个错误的问题。最常见的似乎是 readFile 函数不访问本地文件系统,并且您似乎正在尝试从本地文件系统加载。

这是我过去用来加载 excel 文件然后将每个 sheet 解析为 json 数据的潜在解决方案。注意:这是在 angular 12 项目中,但可以使用相同的 readExcel 函数。

component.html代码:

<input type="file" id="file" multiple (change)="readExcel($event)">

component.ts代码:

import { Component } from '@angular/core';
import * as XLSX from 'xlsx';

@Component({
  selector: 'my-app',
  styleUrls: ['./app.component.scss'],
  templateUrl: './app.component.html',
})
export class AppComponent {
 
  readExcel(event) {

    const file = event.target.files[0];
    const reader: FileReader = new FileReader();

    reader.readAsArrayBuffer(file);
    reader.onload = (e: any) => {

      // upload file
      const binarystr = new Uint8Array(e.target.result);
      const wb: XLSX.WorkBook = XLSX.read(binarystr, { type: 'array', raw: true, cellFormula: false });
      console.log(wb.Sheets)

      const wsname = wb.SheetNames[0];
      const data = XLSX.utils.sheet_to_json(wb.Sheets[wsname]);
      console.log(data)
    }
  }
}

下面是我从测试 excel 文件中使用的测试数据的屏幕截图,其中有两个 sheet,每个 sheet 上有一个 3x3 数据矩阵。

下面是我上传测试 excel 文件时 .json 从上面的 .ts 和 .html 代码输出的屏幕截图。