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?

2
  • Readfile I think can only be used in node. stackoverflow.com/a/57872322/57135 Perhaps? Commented Dec 9, 2020 at 12:42
  • The provided link helped me in getting close to the solution. I am adding it as answer. Thanks Commented Dec 9, 2020 at 13:55

1 Answer 1

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);
Sign up to request clarification or add additional context in comments.

1 Comment

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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.