0

I am working on some react web app in which I am trying to read excel file on client side as below.

import XLSX from "xlsx";

const targetCsvPath = window.location.origin + "/XRayConfig.xlsx";

const workbook = XLSX.readFile(targetCsvPath)

const json = XLSX.utils.sheet_to_json(workbook.Sheets.FOV);

But this gives error TypeError: _fs.readFileSync is not a function. When I run this code snippet using node, it runs flawlessly. I think client side JavaScript does not run on Node, so is the error.

window.location.origin points to public folder of react app and the excel file is in that folder.

This link almost answers this question, but excel file is uploaded from client side using input tag and then it is processed. But My excel file is on server side. How can I solve this?

vaasu varma
  • 85
  • 1
  • 7

1 Answers1

1

I am answering my own question. Using file system APIs does not work on client side JavaScript as it does not run on Node. So first the excel content should be fetched in the form of blob and use that blob. Following solution works for me.

import XLSX from "xlsx";
const targetCsvPath = window.location.origin + "/XRayConfig.xlsx";
const reader = new FileReader();
reader.onload = function (e) {
  const workbook = XLSX.read(e.target.result, { type: "binary" });
   // your operations on workbook comes here
   }

fetch(targetCsvPath)
 .then((response) => response.blob())
  .then((data) => {
    reader.readAsBinaryString(data);
  })
  .catch((err) => console.log(err);
vaasu varma
  • 85
  • 1
  • 7
  • so what cause the error `TypeError: _fs.readFileSync is not a function.`? maybe you can share more about this error in the answer? and not in the question? maybe. – tim Dec 10 '20 at 04:14