当前位置: 首页 > news >正文

使用 React 和 Ant Design 处理 Excel 和 CSV 文件

       在现代 Web 开发中,文件上传和解析是常见的需求。本文将介绍如何使用 React 和 Ant Design 库来处理 Excel 和 CSV 文件的上传,并将提取的表头信息展示在表格中。 

1. 项目基础

确保你已经创建了一个 React 项目,并安装了必要的依赖。可以使用以下命令安装 Ant Design 和 ExcelJS:

npm install antd exceljs

2. 组件结构

我们将构建一个名为 Demo 的组件,该组件包含文件上传功能,并在上传后展示表头信息。

代码结构

import Authority from '@/util/Authority';
import { Button, Table, Upload } from 'antd';
import { ColumnsType } from 'antd/es/table';
import Excel, { CellValue } from 'exceljs';
import { useState } from 'react';const Demo = () => {const [headers, setHeaders] = useState<CellValue[]>([]);const authority = Authority.getInstance();const columns: ColumnsType<Record<string, any>> = [{title: '序号',dataIndex: 'index',key: 'index',align: 'center',render: (text: string, record: any, index: number) => index + 1,},{title: '名称',dataIndex: 'name',align: 'center',key: 'name',},];return (<><UploadmaxCount={1}accept=".xlsx,.csv"showUploadList={false}action="请求地址"headers={{Authorization: 你的token,}}data={(file) => {return {fileName: file.name,mimeType: file.type,};}}onChange={async (info) => {if (info.file.status === 'done') {const file = info.file.originFileObj;const workbook = new Excel.Workbook();const reader = new FileReader();reader.onload = async (e) => {const result = e.target?.result;if (info.file.name.endsWith('.csv')) {// 处理 CSV 文件const lines = (result as string)?.split('\n');const headers = lines[0].split(',');const newHeaders = headers.map((header) => header.trim());setHeaders(newHeaders);} else {// 处理 Excel 文件const buffer = result as ArrayBuffer;if (buffer) await workbook.xlsx.load(buffer);const worksheet = workbook.getWorksheet(1);const headers: CellValue[] = [];worksheet?.getRow(1).eachCell((cell) => {headers.push(cell.value);});setHeaders(headers);}};if (info.file.name.endsWith('.csv')) {reader.readAsText(file!);} else {reader.readAsArrayBuffer(file!);}}}}><Button id="upload">上传</Button></Upload>{headers.length > 0 && (<Tablestyle={{ width: 500 }}rowKey={(record, index) => `header${index}`}columns={columns}dataSource={headers.map((elem, index) => ({index,name: elem,}))}pagination={false}/>)}</>);
};
export default Demo;

3. 代码解析

3.1 组件导入

       我们首先导入了需要的组件和库,包括 Ant Design 的 Upload 和 Table 组件,以及 ExcelJS 用于处理 Excel 文件。

3.2 状态管理

使用 useState 钩子来管理表头数据:

const [headers, setHeaders] = useState<CellValue[]>([]);

3.3 列配置

我们定义了表格列配置,包含序号和名称两列:

const columns: ColumnsType<Record<string, any>> = [{title: '序号',dataIndex: 'index',key: 'index',align: 'center',render: (text: string, record: any, index: number) => index + 1,},{title: '名称',dataIndex: 'name',align: 'center',key: 'name',},
];

3.4 文件上传和解析

Upload 组件用于实现文件上传。我们通过 onChange 事件处理文件的读取和解析:

  • CSV 文件:读取文本并提取表头。
  • Excel 文件:使用 exceljs 库解析并获取第一行内容。

3.5 表格展示

在文件上传并成功解析后,使用 Table 组件展示表头信息。表格的 dataSource 通过 headers 数组动态生成,包含序号和名称。

4.运行效果

上传的源文件:

解析之后的表格

5. 总结

       本文展示了如何使用 React 和 Ant Design 处理文件上传,解析 Excel 和 CSV 文件,并将表头信息以表格形式展示。这个功能在数据管理和报表生成中非常有用。希望本文能帮助你快速实现类似功能,提升你的开发效率!


http://www.mrgr.cn/news/94084.html

相关文章:

  • Linux内核实时机制19 - RT调度器2 - 更新时间 update_curr_rt
  • MySQL中有哪些索引
  • 学习C2CRS Ⅱ (Contrastive Learning Pretraining)
  • MoonSharp 文档三
  • LINUX网络基础 [九] - IP协议
  • LINUX 磁盘和文件系统管理 (二)
  • 【redis】string应用场景:缓存功能和计数功能
  • Vue 侧边栏导航栏 el-menu单个item和多个item
  • 编译skia
  • linux | Vim 命令快捷操作
  • 【漫话机器学习系列】132.概率质量函数(Probability Mass Function, PMF)
  • 搜索 之 组合问题
  • 知识库全链路交互逻辑
  • Linux - 磁盘分区、挂载
  • 自动化测试介绍及学习路线
  • 【贪心算法3】
  • HTMLCSS绘制三角形
  • ubuntu20.04 使用linuxdeployqt打包一个QT程序
  • 数据结构(蓝桥杯常考点)
  • 学习知识的心理和方法杂记-03