How can I read the data in the excel file with reactjs or javascript using the path to the file

2.3k views Asked by At

I want to read the contents of the file directly by using the file path. I can do this by having the file selected. But I don't know how to do it using the direct file path. I could not find any examples or sources for this. Below is how I read the file by selecting it from the input.

import * as XLSX from 'xlsx';
var items = [];

readExcel = (file) => {
const promise = new Promise((resolve, reject) => {
  const fileReader = new FileReader();
  fileReader.readAsArrayBuffer(file);

  fileReader.onload = (e) => {
    const bufferArray = e.target.result;

    const wb = XLSX.read(bufferArray, { type: "buffer" });

    const wsname = wb.SheetNames[0];

    const ws = wb.Sheets[wsname];

    const data = XLSX.utils.sheet_to_json(ws);

    resolve(data);
  };

  fileReader.onerror = (error) => {
    reject(error);
  };
});

promise.then((d) => {
  this.items = d;
  console.log(this.items)

  // fill dictionary
  this.dictionary = Object.assign({}, ...this.items.map((x) => ({ [x.PartNumber]: x.Cost })));
  console.log(this.dictionary)

});

};

<input
        type="file"
        onChange={(e) => {
          const file = e.target.files[0];
          this.readExcel(file);
        }}
      />
2

There are 2 answers

0
hamdi On BEST ANSWER

I couldn't find a direct read operation. I converted the excel file to json format and got my job done.

4
Michael Rovinsky On

I beleive it should work:

const req = new XMLHttpRequest();
req.responseType = "arraybuffer";
req.open("GET", "https://.../MyExcelFile.xlsx", true);

req.onload = () => {
  const bufferArray = req.response;
  const wb = XLSX.read(bufferArray, { type: "buffer" });
  ...