React+Ant Design前端實(shí)現(xiàn)讀取與導(dǎo)出Excel文件
一、前言
在實(shí)際業(yè)務(wù)場景中,我們經(jīng)常需要處理 Excel 文件的導(dǎo)入導(dǎo)出。無論是數(shù)據(jù)填報(bào)、報(bào)表生成還是數(shù)據(jù)分析,Excel 作為一種廣泛使用的電子表格格式,與前端應(yīng)用的結(jié)合愈發(fā)緊密。本文將以 React + Ant Design 項(xiàng)目為例,演示如何通過 xlsx 庫實(shí)現(xiàn)以下功能:
- 讀取本地 XLSX 文件并解析為表格數(shù)據(jù)
- 將表格數(shù)據(jù)導(dǎo)出為 XLSX 文件
二、技術(shù)棧
React: 構(gòu)建用戶界面,憑借其高效的渲染機(jī)制和豐富的生態(tài)系統(tǒng),成為現(xiàn)代 Web 開發(fā)的熱門選擇。
Ant Design: UI 組件庫,提供了一套美觀且易用的 UI 組件,大大加快了開發(fā)速度。
xlsx (SheetJS): Excel 文件處理庫,功能強(qiáng)大,支持多種 Excel 操作,如讀寫、格式化等。
三、準(zhǔn)備工作
1. 創(chuàng)建React項(xiàng)目
npx create-react-app antd-xlsx --template typescript cd antd-xlsx
此命令會創(chuàng)建一個(gè)基于 TypeScript 的 React 項(xiàng)目,并為后續(xù)開發(fā)做好準(zhǔn)備。
2. 安裝依賴
npm install antd @ant-design/icons xlsx
安裝所需的依賴包,包括 Ant Design 組件庫、圖標(biāo)庫以及用于處理 Excel 文件的 xlsx 庫。
3. 目錄結(jié)構(gòu)
src/
├── components/
│ └── XlsxHandler.tsx
├── App.tsx
├── index.tsx
合理的目錄結(jié)構(gòu)有助于項(xiàng)目的組織和維護(hù)。
四、核心實(shí)現(xiàn)
1. 文件讀取模塊
import React, { useState } from 'react';
import { Upload, Table, Button } from 'antd';
import * as XLSX from 'xlsx';
import { InboxOutlined } from '@ant-design/icons';
const XlsxHandler = () => {
const [dataSource, setDataSource] = useState<any[]>([]);
const [headers, setHeaders] = useState<string[]>([]);
// 文件讀取處理
const handleFileChange = (info: any) => {
const file = info.file;
if (!file) return;
// 校驗(yàn)文件類型
const isXlsx = file.name.endsWith('.xlsx') || file.name.endsWith('.xls');
if (!isXlsx) {
info.status = 'error';
info.response = '請選擇正確的Excel文件';
return;
}
const reader = new FileReader();
reader.onload = (e: any) => {
const binaryStr = e.target.result;
const workbook = XLSX.read(binaryStr, { type: 'binary' });
const firstSheetName = workbook.SheetNames[0];
const sheet = workbook.Sheets[firstSheetName];
// 提取表頭
const jsonData = XLSX.utils.sheet_to_json(sheet);
if (jsonData.length > 0) {
setHeaders(Object.keys(jsonData[0]))
setDataSource(jsonData);
}
};
reader.readAsBinaryString(file);
};
// 數(shù)據(jù)導(dǎo)出功能
const exportToExcel = () => {
const ws = XLSX.utils.json_to_sheet(dataSource);
const wb = XLSX.utils.book_new();
XLSX.utils.book_append_sheet(wb, ws, 'ExportedData');
XLSX.writeFile(wb, `export_${Date.now()}.xlsx`);
};
return (
<div style={{ padding: 20 }}>
<Upload
beforeUpload={handleFileChange}
showUploadList={false}
maxCount={1}
accept=".xlsx,.xls"
>
<Button icon={<InboxOutlined />}>選擇Excel文件</Button>
</Upload>
{headers.length > 0 && (
<Table
dataSource={dataSource}
rowKey="id"
pagination={{ pageSize: 10 }}
style={{ marginTop: 20 }}
>
{headers.map((header) => (
<Table.Column key={header} title={header} dataIndex={header} />
))}
</Table>
)}
<Button
type="primary"
onClick={exportToExcel}
disabled={!headers.length}
style={{ marginTop: 20 }}
icon={<DownloadOutlined />}
>
導(dǎo)出當(dāng)前數(shù)據(jù)
</Button>
</div>
);
};
export default XlsxHandler;
2. 主應(yīng)用集成
import React from 'react';
import './App.css';
import { ConfigProvider } from 'antd';
import XlsxHandler from './components/XlsxHandler';
import { DownloadOutlined } from '@ant-design/icons';
function App() {
return (
<ConfigProvider>
<div className="App">
<h1>Excel文件處理示例</h1>
<XlsxHandler />
</div>
</ConfigProvider>
);
}
export default App;
五、技術(shù)要點(diǎn)解析
1. 文件讀取流程
- 使用HTML5的File API獲取文件對象
- 通過FileReader讀取二進(jìn)制內(nèi)容
- 使用SheetJS解析二進(jìn)制流生成工作簿
- 提取第一個(gè)工作表的數(shù)據(jù)
- 轉(zhuǎn)換為JSON格式渲染表格
2. 數(shù)據(jù)導(dǎo)出流程
- 將JSON數(shù)據(jù)轉(zhuǎn)換為工作表
- 創(chuàng)建新的工作簿并添加工作表
- 使用writeFile方法生成Excel文件
3. 關(guān)鍵技術(shù)點(diǎn)
- 二進(jìn)制處理:必須使用
readAsBinaryString方法讀取文件 - 鍵值映射:JSON字段名對應(yīng)Excel列名
- 類型校驗(yàn):嚴(yán)格校驗(yàn)文件擴(kuò)展名防止格式錯(cuò)誤
- 內(nèi)存優(yōu)化:及時(shí)釋放FileReader實(shí)例避免內(nèi)存泄漏
到此這篇關(guān)于React+Ant Design前端實(shí)現(xiàn)讀取與導(dǎo)出Excel文件的文章就介紹到這了,更多相關(guān)React讀取與導(dǎo)出Excel內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
淺析history 和 react-router 的實(shí)現(xiàn)原理
react-router 版本更新非???但是它的底層實(shí)現(xiàn)原理確是萬變不離其中,在本文中會從前端路由出發(fā)到 react-router 原理總結(jié)與分享,本文對history 和 react-router實(shí)現(xiàn)原理講解的非常詳細(xì),需要的朋友跟隨小編一起看看吧2023-08-08
React組件三大核心屬性State?props?Refs介紹
組件實(shí)例的三大核心屬性是:State、Props、Refs。類組件中這三大屬性都存在。函數(shù)式組件中訪問不到?this,也就不存在組件實(shí)例這種說法,但由于它的特殊性(函數(shù)可以接收參數(shù)),所以存在Props這種屬性2023-02-02
詳解如何在React中優(yōu)雅的使用addEventListener
這篇文章主要為大家詳細(xì)介紹了如何在React中優(yōu)雅的使用addEventListener,文中的示例代碼簡潔易懂,對大家學(xué)習(xí)React有一定的幫助,需要的可以參考一下2023-01-01

