问题描述
我是ReactJS的新手,我想读取Excel文件并在react项目中显示数据。为此,我可以从excel文件中成功读取数据。现在,问题是我无法在react项目上显示数据。我搜索了这个问题,发现没有像这样定义数组值...
帮我在React项目中显示数据。
import React from 'react'
import { Table } from 'react-bootstrap'
import * as XLSX from 'xlsx'
import Accordion from './component/accordion'
import './App.css'
function App() {
var items = [];
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 = {SheetNames:[],Sheets:{}};
const ws1 = XLSX.read(bufferArray,{type:"buffer"}).Sheets.Sheet1;
const ws2 = XLSX.read(bufferArray,{type:"buffer"}).Sheets.Sheet2;
wb.SheetNames.push("Sheet1"); wb.Sheets["Sheet1"] = ws1;
wb.SheetNames.push("Sheet2"); wb.Sheets["Sheet2"] = ws2;
const data1 = XLSX.utils.sheet_to_json(ws1);
const data2 = XLSX.utils.sheet_to_json(ws2);
resolve([data1,data2]);
};
fileReader.onerror=(error) => {
reject(error);
};
});
promise.then((excelData) => {
items.push(excelData);
console.log(excelData);
});
};
return(
<div className="container-fluid">
<section className="heading">
<h4>Products Details</h4>
<input type="file" className="input-field" onChange={(e) =>{
const file=e.target.files[0];
readExcel(file);
}} />
</section>
{items.map((d) => (
<Accordion
title={
<div>
<tr key={d.ID} className="btn-heading">
<td>{d.ID}</td>
<td>{d.Mail}</td>
<td>{d.Name}</td>
<td>{d.PhoneNo}</td>
<td>{d.City}</td>
<td>{d.Date}</td>
<td>{d.Time}</td>
</tr>
</div>
}
content={
<div>
<p className="header">
<span className="header-content">Shipping Address:</span>
292 Naqshband Colony. Near rabbania Mosque. Multan
</p>
<Table size="sm">
<thead>
<tr>
<th>#</th>
<th>Article No</th>
<th>Product Name</th>
<th>Quantity</th>
<th>Price</th>
<th>Total Amount</th>
</tr>
</thead>
<tbody>
{items.map((c) =>(
<tr key={c.ArticleNo}>
<td>{c.ArticleNo}</td>
<td>{c.ProductName}</td>
<td>{c.Quantity}</td>
<td>{c.Price}</td>
<td>{c.TotalAmount}</td>
</tr>
))}
</tbody>
</Table>
</div>
}
/>
))}
</div>
);
}
export default App;
以下是代码和答案:https://codesandbox.io/s/tender-tharp-30t8j?file=/src/App.js
解决方法
好吧,我已经尝试过,并且在控制台中看到了该错误
这是您需要做的
- 将键移动到手风琴(正在映射的组件)
- 确保您的Excel工作表标题与您在下面使用的键名匹配
键必须是地图内的组件。
此外,名称 Sheet1 应该是工作表的名称
{items.map((d) => (
<Accordion key={d.ID} <-- move the key to here,title={
<div>
<tr className="btn-heading">
<td>{d.ID}</td> <-- These values should exactly match *headers of your excel sheet
<td>{d.Mail}</td>
<td>{d.Name}</td>
<td>{d.PhoneNo}</td>
<td>{d.City}</td>
<td>{d.Date}</td>
<td>{d.Time}</td>
</tr>
</div>
}
....
如果仍然遇到问题,请与示例数据共享一个excel表。