Uploda

beforeUpload: () => false 手动上传,阻止自动的 action 上传

showUploadList: false
image.png

event 上传文件信息

image.png

  1. {
  2. "file": { "uid": "rc-upload-1701008812275-2" },
  3. "fileList": [
  4. {
  5. "uid": "rc-upload-1701008812275-2",
  6. "lastModified": 1701008651059,
  7. "lastModifiedDate": "2022-11-26T14:24:11.059Z",
  8. "name": "用户.xlsx",
  9. "size": 8825,
  10. "type": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
  11. "percent": 0,
  12. "originFileObj": { "uid": "rc-upload-1701008812275-2" }
  13. }
  14. ]
  15. }

用户.xlsx
image.png

xlsx.read

sheet_to_json

const json = utils.sheet_to_json(worksheet) 获取到的数据,不带表头
image.png

新增 header 字段参数后,替换的数据,多了表头的数据

  1. const json = utils.sheet_to_json(worksheet, {
  2. header: ['name', 'phone', 'age'],
  3. rawNumbers: true,
  4. range: 1, // 跳过表头
  5. });

image.png

  1. 不带 header 参数,需要自己手动的替换为数据库的字段
  2. 带上 header 参数后,需要过滤掉第一行的表头,或 range: 1 跳过第一行

customRequest

https://github.com/react-component/upload#customrequest
https://3x.ant.design/components/upload-cn/#customRequest

  1. import React from 'react';
  2. import { Button, Upload } from 'antd';
  3. import { UploadOutlined } from '@ant-design/icons';
  4. import type { UploadProps, UploadChangeParam, UploadFile } from 'antd/lib/upload';
  5. import { read, utils } from 'xlsx'
  6. import { readFile } from './utils'
  7. const props: UploadProps = {
  8. name: 'file',
  9. // 上传的文件类型
  10. accept: '.xlsx, .xls, .csv, application/vnd.ms-excel',
  11. showUploadList: false,
  12. headers: {
  13. authorization: 'authorization-text',
  14. },
  15. // beforeUpload 返回 false 后,手动上传
  16. beforeUpload: () => false,
  17. onChange: async (event: UploadChangeParam) => {
  18. const { file, fileList } = event;
  19. const data = await readFile(file)
  20. console.log({ file, fileList, data })
  21. const workbook = read(data, { type: 'binary' });
  22. const { Sheets, SheetNames } = workbook;
  23. const worksheet = Sheets[SheetNames[0]];
  24. const json = utils.sheet_to_json(worksheet, {
  25. header: ['name', 'phone', 'age'],
  26. rawNumbers: false,
  27. range: 1,
  28. });
  29. },
  30. };
  31. const UploadExcel: React.FC = () => {
  32. return (
  33. <Upload {...props}>
  34. <Button
  35. type='primary'
  36. icon={<UploadOutlined />}
  37. >
  38. 上传 Excel
  39. </Button>
  40. </Upload>
  41. )
  42. };
  43. export default UploadExcel