2

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;
0

1 Answer 1

3

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

This github issue seems to discuss issues around this error. Most commonly 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.

component.html code:

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

component.ts code:

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

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.

enter image description here

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

enter image description here

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.