日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

React?全面解析excel文件_React

作者:摸魚第一人 ? 更新時間: 2022-11-07 編程語言

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

欄目分類
最近更新