1

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

1 Answers1

0

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" });
  ...
Michael Rovinsky
  • 3,980
  • 3
  • 11
  • 23
  • I need to read it from a local file. That's why I don't think I can make a get request. This file will be constantly updated and it would be pointless to keep it on web servers. for example; C: \ abc.xlsx – HAMDİ DAMAR May 02 '21 at 08:13
  • Well, I suppose I did not understand your question properly. You want to access a file in the client's file system from a browser without picking it in an `open file` dialog? – Michael Rovinsky May 02 '21 at 08:23
  • Yes, for example, I need to read the data in an excel file in the c directory directly via the file path with reactjs or javascript. In other words, the user should not select that file and should read it directly when the web project is opened. – HAMDİ DAMAR May 02 '21 at 08:29
  • I'm not sure it's possible at all. Browsers have a very limited access to the client's file system because of security considerations. – Michael Rovinsky May 02 '21 at 08:51