【问题标题】:Reading Excel file in client side JavaScript在客户端 JavaScript 中读取 Excel 文件
【发布时间】:2021-03-20 18:47:03
【问题描述】:

我正在开发一些反应网络应用程序,我试图在客户端读取 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);

但这会产生错误TypeError: _fs.readFileSync is not a function。当我使用节点运行此代码 sn-p 时,它运行完美。我认为客户端 JavaScript 不能在 Node 上运行,错误也是如此。

window.location.origin指向react app的public文件夹,excel文件就在那个文件夹里。

这个link几乎回答了这个问题,但是excel文件是从客户端使用输入标签上传的,然后被处理。但我的 excel 文件在服务器端。我该如何解决这个问题?

【问题讨论】:

  • Readfile 我认为只能在node.js中使用。 stackoverflow.com/a/57872322/57135 也许?
  • 提供的链接帮助我接近解决方案。我将其添加为答案。谢谢

标签: javascript html node.js reactjs xlsx


【解决方案1】:

我正在回答我自己的问题。使用文件系统 API 不适用于客户端 JavaScript,因为它不在 Node.js 上运行。因此,首先应该以 blob 的形式获取 excel 内容并使用该 blob。 以下解决方案对我有用。

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

【讨论】:

  • 那么导致错误TypeError: _fs.readFileSync is not a function.的原因是什么?也许您可以在答案中分享更多有关此错误的信息?而不是问题?也许吧。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-09-16
  • 2014-08-30
  • 1970-01-01
  • 1970-01-01
  • 2011-06-24
相关资源
最近更新 更多