简体   繁体   English

如何使用 reactjs 或 javascript 使用文件路径读取 excel 文件中的数据

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

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

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" });
  ...

I couldn't find a direct read operation.我找不到直接读取操作。 I converted the excel file to json format and got my job done.我将 excel 文件转换为 json 格式并完成了我的工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM