Javascript 在 Reactjs 中读取 excel 文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/46909260/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 03:39:51  来源:igfitidea点击:

Reading excel file in Reactjs

javascriptjqueryexcelreactjs

提问by Noman Ali

I am trying and banging my head already while trying to read excel file in Reactjs.

在尝试在 Reactjs 中读取 excel 文件时,我已经在尝试和敲我的头了。

I have tried multiple libraries out there like, Sheetjs, excel-parser, exceljsand so on (like 8-9) libraries.

我已经尝试了多个库,比如Sheetjsexcel-parserexceljs等等(比如 8-9)库。

I am getting weird and different errors in every library.

我在每个库中都遇到了奇怪且不同的错误。

For example i am using excel-parserand getting following error

例如,我正在使用excel-parser并收到以下错误

Module not found: 'child_process'

That is because it is a node module and won't work in browser.

那是因为它是一个节点模块,不能在浏览器中工作。

Anyone know some good and easy library that can work with reactjs in browser?

任何人都知道一些可以在浏览器中使用reactjs 的好而简单的库?

回答by Noman Ali

I have successfully read excel file using Sheetjs's npm version xlsx.

我已经使用Sheetjs的 npm 版本xlsx成功读取了 excel 文件。

Here is code:

这是代码:

import * as XLSX from 'xlsx';
//f = file
var name = f.name;
const reader = new FileReader();
reader.onload = (evt) => { // evt = on_file_select event
    /* Parse data */
    const bstr = evt.target.result;
    const wb = XLSX.read(bstr, {type:'binary'});
    /* Get first worksheet */
    const wsname = wb.SheetNames[0];
    const ws = wb.Sheets[wsname];
    /* Convert array of arrays */
    const data = XLSX.utils.sheet_to_csv(ws, {header:1});
    /* Update state */
    console.log("Data>>>"+data);
};
reader.readAsBinaryString(f);

回答by Янов Алексей

Noman Ali! Thank you.
I used, this code

诺曼阿里!谢谢你。
我用过,这个代码

const handleUpload = (e) => {
    e.preventDefault();

    var files = e.target.files, f = files[0];
    var reader = new FileReader();
    reader.onload = function (e) {
        var data = e.target.result;
        let readedData = XLSX.read(data, {type: 'binary'});
        const wsname = readedData.SheetNames[0];
        const ws = readedData.Sheets[wsname];

        /* Convert array to json*/
        const dataParse = XLSX.utils.sheet_to_json(ws, {header:1});
        setFileUploaded(dataParse);
    };
    reader.readAsBinaryString(f)
}

回答by itch96

I find xlsx to work pretty well. xlsx Package

我发现 xlsx 工作得很好。 xlsx 包