網站首頁 編程語言 正文
React解析excel文件
首先安裝安裝xlsx插件
yarn add xlsx
使用xlsx解析
? ? /**
? ? ?* 上傳文件并解析成json
? ? ?*/
? ? const HandleImportFile = (info) => {
? ? ? ? let files = info.file;
? ? ? ? // 獲取文件名稱
? ? ? ? let name = files.name
? ? ? ? // 獲取文件后綴
? ? ? ? let suffix = name.substr(name.lastIndexOf("."));
? ? ? ? let reader = new FileReader();
? ? ? ? reader.onload = (event) => {
? ? ? ? ? ? try {
? ? ? ? ? ? ? ? // 判斷文件類型是否正確
? ? ? ? ? ? ? ? if (".xls" != suffix && ".xlsx" != suffix) {
? ? ? ? ? ? ? ? ? ? message.error("選擇Excel格式的文件導入!");
? ? ? ? ? ? ? ? ? ? return false;
? ? ? ? ? ? ? ? }
? ? ? ? ? ? ? ? let { result } = event.target;
? ? ? ? ? ? ? ? // 讀取文件
? ? ? ? ? ? ? ? let workbook = XLSX.read(result, { type: 'binary' });
? ? ? ? ? ? ? ? let data = [];
? ? ? ? ? ? ? ? // 循環文件中的每個表
? ? ? ? ? ? ? ? for (let sheet in workbook.Sheets) {
? ? ? ? ? ? ? ? ? ? if (workbook.Sheets.hasOwnProperty(sheet)) {
? ? ? ? ? ? ? ? ? ? ? ? // 將獲取到表中的數據轉化為json格式
? ? ? ? ? ? ? ? ? ? ? ? data = data.concat(XLSX.utils.sheet_to_json(workbook.Sheets[sheet]));
? ? ? ? ? ? ? ? ? ? }
? ? ? ? ? ? ? ? }
? ? ? ? ? ? ? ? console.log('data:', data);
? ? ? ? ? ? } catch (e) {
? ? ? ? ? ? ? ? message.error('文件類型不正確!');
? ? ? ? ? ? }
? ? ? ? }
? ? ? ? reader.readAsBinaryString(files);
? ? ? ? setIsLoading(false);
? ? }
使用antd的Upload組件上傳文件
?<Upload
? ? accept=".xls , .xlsx"
? ? maxCount={1}
? ? showUploadList={false}
? ? customRequest={HandleImportFile}
? >
? ?<Button icon={<UploadOutlined />} type="primary">上傳文件</Button>
?</Upload>
React上傳excel預覽
import React from 'react';
import * as XLSX from 'xlsx';
import {message, Table, Upload} from 'antd';
const { Dragger } = Upload;
export class UploadFile extends React.Component {
state = {
tableData: [],
tableHeader: []
};
toReturn = () => {
this.props.close();
};
toSubmit = () => {
const _this = this;
console.log(_this.state.tableData);
};
render() {
return (
<div>
<Dragger name="file"
accept=".xls,.xlsx" maxCount={1}
beforeUpload={function () {
return false;
}}
onChange={this.uploadFilesChange.bind(this)}
showUploadList={false}>
<p className="ant-upload-text">
<span>點擊上傳文件</span>
或者拖拽上傳
</p>
</Dragger>
<Table
columns={this.state.tableHeader}
dataSource={this.state.tableData}
style={{marginTop: '20px'}}
pagination={false}
/>
</div>
);
}
uploadFilesChange(file) {
// 通過FileReader對象讀取文件
const fileReader = new FileReader();
// 以二進制方式打開文件
fileReader.readAsBinaryString(file.file);
fileReader.onload = event => {
try {
const {result} = event.target;
// 以二進制流方式讀取得到整份excel表格對象
const workbook = XLSX.read(result, {type: 'binary'});
// 存儲獲取到的數據
let data = {};
// 遍歷每張工作表進行讀?。ㄟ@里默認只讀取第一張表)
for(const sheet in workbook.Sheets) {
let tempData = [];
// esline-disable-next-line
if(workbook.Sheets.hasOwnProperty(sheet)) {
// 利用 sheet_to_json 方法將 excel 轉成 json 數據
console.log(sheet);
data[sheet] = tempData.concat(XLSX.utils.sheet_to_json(workbook.Sheets[sheet]));
}
}
const excelData = data.Sheet1;
const excelHeader = [];
// 獲取表頭
for(const headerAttr in excelData[0]) {
const header = {
title: headerAttr,
dataIndex: headerAttr,
key: headerAttr
};
excelHeader.push(header);
}
// 最終獲取到并且格式化后的 json 數據
this.setState({
tableData: excelData,
tableHeader: excelHeader,
});
console.log(this.state);
} catch(e) {
// 這里可以拋出文件類型錯誤不正確的相關提示
console.log(e);
message.error('文件類型不正確!');
}
};
}
}
export default UploadFile;
原文鏈接:https://blog.csdn.net/xJ_fang/article/details/124190122
相關推薦
- 2022-01-14 path.join()和path.resolve()區別
- 2021-12-02 Golang共享變量如何解決問題_Golang
- 2023-01-09 基于Go語言實現插入排序算法及優化_Golang
- 2022-12-26 使用python如何對圖片進行壓縮_python
- 2022-09-14 Python最好的日期處理庫pendulum的使用指南_python
- 2022-08-29 Python基礎語法之變量與數據類型詳解_python
- 2022-09-14 jQuery實現簡單計算器功能_jquery
- 2022-04-08 WPF布局及布局容器介紹_基礎應用
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支