Uploda
beforeUpload: () => false 手动上传,阻止自动的 action 上传
showUploadList: false
event 上传文件信息
{
"file": { "uid": "rc-upload-1701008812275-2" },
"fileList": [
{
"uid": "rc-upload-1701008812275-2",
"lastModified": 1701008651059,
"lastModifiedDate": "2022-11-26T14:24:11.059Z",
"name": "用户.xlsx",
"size": 8825,
"type": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
"percent": 0,
"originFileObj": { "uid": "rc-upload-1701008812275-2" }
}
]
}
用户.xlsx
xlsx.read
sheet_to_json
const json = utils.sheet_to_json(worksheet) 获取到的数据,不带表头
新增 header 字段参数后,替换的数据,多了表头的数据
const json = utils.sheet_to_json(worksheet, {
header: ['name', 'phone', 'age'],
rawNumbers: true,
range: 1, // 跳过表头
});
�
- 不带 header 参数,需要自己手动的替换为数据库的字段
- 带上 header 参数后,需要过滤掉第一行的表头,或 range: 1 跳过第一行
customRequest
https://github.com/react-component/upload#customrequest
https://3x.ant.design/components/upload-cn/#customRequest
import React from 'react';
import { Button, Upload } from 'antd';
import { UploadOutlined } from '@ant-design/icons';
import type { UploadProps, UploadChangeParam, UploadFile } from 'antd/lib/upload';
import { read, utils } from 'xlsx'
import { readFile } from './utils'
const props: UploadProps = {
name: 'file',
// 上传的文件类型
accept: '.xlsx, .xls, .csv, application/vnd.ms-excel',
showUploadList: false,
headers: {
authorization: 'authorization-text',
},
// beforeUpload 返回 false 后,手动上传
beforeUpload: () => false,
onChange: async (event: UploadChangeParam) => {
const { file, fileList } = event;
const data = await readFile(file)
console.log({ file, fileList, data })
const workbook = read(data, { type: 'binary' });
const { Sheets, SheetNames } = workbook;
const worksheet = Sheets[SheetNames[0]];
const json = utils.sheet_to_json(worksheet, {
header: ['name', 'phone', 'age'],
rawNumbers: false,
range: 1,
});
},
};
const UploadExcel: React.FC = () => {
return (
<Upload {...props}>
<Button
type='primary'
icon={<UploadOutlined />}
>
上传 Excel
</Button>
</Upload>
)
};
export default UploadExcel