背景:运营要求上传excel表格并解析成表格展示
// 引入解析插件
import * as XLSX from 'xlsx';
// 解析excel表
const uploadProps = {
accept: '.xlsx',
beforeUpload: (file: any) => {
const f = file;
const reader = new FileReader();
reader.onload = function (e: any) {
const datas = e.target.result;
const workbook = XLSX.read(datas, {
type: 'binary',
}); // 尝试解析datas
const first_worksheet = workbook.Sheets[workbook.SheetNames[0]]; // 是工作簿中的工作表的有序列表
const jsonArr: Array<string[]> = XLSX.utils.sheet_to_json(first_worksheet, {
header: 1,
}); // 将工作簿对象转换为JSON对象数组
const filterArr = jsonArr.filter((item: any) => item.length !== 0);
// 去掉表头
filterArr.shift();
// 将解析出的数据作为表数据
filterArr.map((item: any, index: number) => {
uploadTable.push({
id: new Date().getTime() + index, // 删除标记
goods_thumbnail: item[0], // 商品图片地址
goods_name: item[1], // 商品名称
coupon_price: item[2], // 券后价
price: item[3], // 商品原价
start_time: `${item[4]} 00:00:00`, // 开始时间
end_time: `${item[5]} 00:00:00`, // 结束时间
jump_url: item[6], // 跳转地址
});
return false;
});
// 展示读取的数据
setGoodsData(uploadTable);
};
reader.readAsBinaryString(f);
return false;
},
showUploadList: false,
};
结合antd上传组件
<Upload {...uploadProps}>
<Button>
<Icon type="upload" />上传文件(仅支持xlsx)
</Button>
</Upload>
中间处理数据的逻辑需要换成自己的