首先安装 xlsx
npm install xlsx
项目中引入
import XLSX from 'xlsx';
上传组件,因为懒得写样式,这里使用的 antd 的 Upload 组件,使用 <input type="file" /> 也是可以的。
使用 customRequest 自定义上传
<Upload name="file" accept=".xls,.xlsx" showUploadList={false} customRequest={upload} > <span className={cns(style.btn, style.import)}> <img src={importPNG}/> <span>导入数据</span> </span> </Upload>
核心代码,解析 excel
const upload = (e) => { const f = e.file; const reader = new FileReader(); // 使用 FileReader 读取数据 reader.onload = function(e) { // 数据读取完成后的回调函数 const data = new Uint8Array(e.target.result); const workbook = XLSX.read(data, {type: 'array'}); // workbook 是 xlsx 解析 excel 后返回的对象 const firstSheetName = workbook.SheetNames[0]; // 获取第一个 sheet 的名字 const worksheet = workbook.Sheets[firstSheetName]; // 获取第一个 sheet 的内容 const res = XLSX.utils.sheet_to_json(worksheet); // 使用 utils 里的方法转换内容为便于使用的数组 // 下面就是自己对数组进行操作就行了 const list = res.map(item => { return { keyword: item.keyword, weight: item.weight } }); wordObj.setKeys([...wordObj.keys, ...list]); }; reader.readAsArrayBuffer(f); // 读取数据 };