简体   繁体   English

在客户端读取 Excel 文件 JavaScript

[英]Reading Excel file in client side JavaScript

I am working on some react web app in which I am trying to read excel file on client side as below.我正在开发一些反应 web 应用程序,我正在尝试在客户端读取 excel 文件,如下所示。

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 .但这会产生错误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.我认为客户端 JavaScript 不在 Node 上运行,错误也是如此。

window.location.origin points to public folder of react app and the excel file is in that folder. window.location.origin指向 react 应用程序的公共文件夹,excel 文件位于该文件夹中。

This link almost answers this question, but excel file is uploaded from client side using input tag and then it is processed.这个链接几乎回答了这个问题,但是 excel 文件是使用输入标签从客户端上传然后处理的。 But My excel file is on server side.但是我的 excel 文件在服务器端。 How can I solve this?我该如何解决这个问题?

I am answering my own question.我正在回答我自己的问题。 Using file system APIs does not work on client side JavaScript as it does not run on Node.使用文件系统 API 在客户端 JavaScript 上不起作用,因为它不在 Node.js 上运行。 So first the excel content should be fetched in the form of blob and use that blob.因此,首先应该以 blob 的形式获取 excel 内容并使用该 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);

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

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