1. 程式人生 > 實用技巧 >匯入上傳excel後,如果是多個sheet,需要支援選擇匯入哪個sheet

匯入上傳excel後,如果是多個sheet,需要支援選擇匯入哪個sheet

(此借鑑別人家的...........)


一.需要處理的Excel


二.React程式碼實現

import React from 'react';
import XLSX from 'xlsx';
class Guide extends React.Component {
    constructor(props) {
        super(props);
    }
// 匯入xlsx
importExcel=(file)=> {
    // 獲取上傳的檔案物件
    const { files } = file.target;
    // 通過FileReader物件讀取檔案
    const fileReader = new
FileReader(); fileReader.onload = event => { try { const { result } = event.target; //以二進位制流方式讀取得到整份excel表格物件 const workbook = XLSX.read(result, { type: 'binary' }); console.log(workbook,'workbook') let data = []; //儲存獲取到的資料 // 遍歷每張工作表進行讀取(這裡預設只讀取第一張表)
for (const sheet in workbook.Sheets) { if (workbook.Sheets.hasOwnProperty(sheet)) { // 利用 sheet_to_json 方法將 excel 轉成 json 資料 data = data.concat(XLSX.utils.sheet_to_json(workbook.Sheets[sheet])); // break; // 如果只取第一張表,就取消註釋這行 } } console.log(data); }
catch (e) { // 丟擲檔案型別錯誤不正確的相關提示 console.log('檔案型別不正確'); return; } }; // 以二進位制方式開啟檔案 fileReader.readAsBinaryString(files[0]); }; render = () => { return ( <div className="logon-guide"> <input type='file' accept='.xlsx, .xls' onChange={(e) => {this.importExcel(e)}} /> </div> ) } } export default Guide;

三.返回json格式如下