如何使用react.js上传Excel表格文件并将数据显示到表格中

10

我是React JS的新手。我正在尝试使用React.js上传Excel表格文件并将数据显示到表格中。我从链接中得到了部分参考,但它并不完整。请帮忙解决。 从Excel导入数据并在React组件中显示


请查看此链接:https://dev59.com/OVYN5IYBdhLWcg3wx6sR - tarzen chugh
6个回答

8

react-excel-renderer

这里有一个完美的库可以实现这个功能!它首先将Excel数据转换为JSON,然后将其渲染为HTML表格。它叫做react-excel-renderer

  • Install it npm install react-excel-renderer --save

  • Import both components ExcelRenderer and OutTable

    import {ExcelRenderer, OutTable} from 'react-excel-renderer';

  • Provide the file object to the ExcelRenderer function in your event handler

      fileHandler = (event) => {
    let fileObj = event.target.files[0];
    
    //just pass the fileObj as parameter
    ExcelRenderer(fileObj, (err, resp) => {
      if(err){
        console.log(err);            
      }
      else{
        this.setState({
          cols: resp.cols,
          rows: resp.rows
        });
      }
    });               
    
    }
    
  • Once JSON is obtained, provide it to the OutTable component
    <OutTable data={this.state.rows} columns={this.state.cols} tableClassName="ExcelTable2007" tableHeaderRowClass="heading" />

这就是它!完成了!可以在这里找到相关演示。关于此的详细信息,请参考下文。

1
太好了!它是否支持从文档中的多个工作表读取数据呢? - Sachin Pakale
有没有办法从后端API调用获取Excel文件,然后在前端呈现?我查看了您的示例,发现它是针对从文件浏览器中选择文件的情况。 - tejesh
1
只要你能获取文件 blob,无论是从文件浏览器还是后端 API,都是可能的。 - Ashish Deshpande
@sachin:如果你指的是工作簿,那么目前它只支持单个工作簿。 - Ashish Deshpande
1
@AshishDeshpande 谢谢! 我做了一些变通,修改了你的示例。现在它可以正常工作了。 我创建了文件对象而不是 blob,然后直接将该对象传递给 filerender 函数。 - tejesh

4
我使用xlsx成功地读取了Excel文件的工作表。 只需像这样操作:
import excel from 'xlsx';
let fileName = "newData.xlsx";
let workbook = excel.readFile(fileName);
console.log(workbook) //should print an array with the excel file data

假设您的根目录中有名为'newData.xlsx'的电子表格。然后只是需要找出如何访问您想要的数据。这个也应该会有所帮助。

2
我在控制台中收到了以下错误信息:Uncaught TypeError: _fs.readFileSync 不是一个函数。 - Mansi
1
回顾过去,我认为这只适用于Node或其他服务器端部署。如果你想在浏览器中使用XLSX,你将不得不使用FileReader。 - WebbH

2
我在扩展@AshishDeshpande的答案,我使用了相同的库react-excel-renderer。如果您从后端API调用中获得文件,则可以使用axios执行以下操作:如果我们检查@AshishDeshpande的演示代码,

https://github.com/ashishd751/excel-renderer-demo/blob/master/src/App.js

我在openFileBrowser()函数中添加了fileHandler()函数。
openFileBrowser = () => {
        
      axios({
        url:'http://127.0.0.1:5000/display',
        method:'GET',
        responseType: 'blob'
      })
      .then((response) => {
                  const url = (new File([response.data], "file.xlsx", {type:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", lastModified:new Date().getTime()}));

                  console.log(url);
                 
                  let fileName = url.name;
                  console.log(url);
                  
                  //check for file extension and pass only if it is .xlsx and display error message otherwise
                  if(fileName.slice(fileName.lastIndexOf('.')+1) === "xlsx"){
                    this.setState({
                      uploadedFileName: fileName,
                      isFormInvalid: false
                    });
                    this.renderFile(url)
                  }    
                  else{
                    this.setState({
                      isFormInvalid: true,
                      uploadedFileName: ""
                    })
                  }
                 
                  
    })
    }

可以更新为:axios.get("/display", { //url:'http://127.0.0.1:5000/display', method:'GET', responseType: 'blob' })然后,在 package.json 中添加 "proxy": "http://127.0.0.1:5000"。 - tejesh

1
制作React应用程序,然后将此代码添加到app.js中,只需更改列名(例如InputA和InputB),这些是我使用的,如果您想添加其他列,可以这样做。 希望这可以帮助您。请随意评论(这是我在stackoverflow上的第一个答案)。
import React, { useState } from "react";
import "./App.css";
import * as XLSX from "xlsx";
function App() {
  const [items, setItems] = useState([]);

  const 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) => {
      setItems(d);
    });
  };

  return (
    <div>
      <input
        type="file"
        onChange={(e) => {
          const file = e.target.files[0];
          readExcel(file);
        }}
      />

      <table class="table container">
        <thead>
          <tr>
            <th scope="col">InputA</th>
            <th scope="col">InputB</th>
          </tr>
        </thead>
        <tbody>
          {items.map((d) => (
            <tr key={d.InputA}>
              <th>{d.InputA}</th>
              <td>{d.InputB}</td>
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  );
}

export default App;

0

但是我们如何使用React Dropzone库“读取”和保存数据呢?https://stackoverflow.com/questions/68069700/read-display-excel-file-in-react - user13067694

-2

需要datetime模块

const parseDate = v => {
  const d = v - 1;
  const t = Math.round((d - Math.floor(d)) * 24 * 60 * 60);
  console.log('parseDate d ', d, 't', t);
  return moment(new Date(1900, 0, d, 0, 0, t)).format('YYYY-MM-DD');
};

const dateStr = parseDate(43523);
console.log('dateStr ', dateStr)
<script src="https://momentjs.com/downloads/moment.js"></script>


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接