最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Converting Excel Data to JSON using SHEETJS - Stack Overflow

programmeradmin1浏览0评论

I am trying to convert my excel file to JSON using SHEETJS but it showing that fs.readFileSync is not a function.

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;

I am trying to convert my excel file to JSON using SHEETJS but it showing that fs.readFileSync is not a function.

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;
Share Improve this question asked Aug 20, 2021 at 17:40 srksrk 1903 silver badges17 bronze badges 0
Add a ment  | 

1 Answer 1

Reset to default 3

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

This github issue seems to discuss issues around this error. Most monly seems to be that the readFile function does not access local file system and it seems like you are trying to load from a local file system.

Here is a potential solution that I have used in the past to load an excel file then parse each sheet into json data. NOTE: this was in an angular 12 project but the same readExcel function can be used.

ponent.html code:

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

ponent.ts code:

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

@Component({
  selector: 'my-app',
  styleUrls: ['./app.ponent.scss'],
  templateUrl: './app.ponent.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)
    }
  }
}

Below is a screenshot of the test data I used from a test excel file that had two sheets in it with a 3x3 matrix of data on each sheet.

Below is a screenshot of the .json output form the .ts and .html code above when I uploaded the test excel file.

发布评论

评论列表(0)

  1. 暂无评论