首先安裝 xlsx
npm install xlsx
項目中引入
import XLSX from 'xlsx';
上傳組件,因為懶得寫樣式,這里使用的 antd 的 Upload 組件,使用 <input type="file" /> 也是可以的。
使用 customRequest 自定義上傳
<Upload name="file" accept=".xls,.xlsx" showUploadList={false} customRequest={upload} > <span className={cns(style.btn, style.import)}> <img src={importPNG}/> <span>導入數據</span> </span> </Upload>
核心代碼,解析 excel
const upload = (e) => { const f = e.file; const reader = new FileReader(); // 使用 FileReader 讀取數據 reader.onload = function(e) { // 數據讀取完成后的回調函數 const data = new Uint8Array(e.target.result); const workbook = XLSX.read(data, {type: 'array'}); // workbook 是 xlsx 解析 excel 后返回的對象 const firstSheetName = workbook.SheetNames[0]; // 獲取第一個 sheet 的名字 const worksheet = workbook.Sheets[firstSheetName]; // 獲取第一個 sheet 的內容 const res = XLSX.utils.sheet_to_json(worksheet); // 使用 utils 里的方法轉換內容為便於使用的數組 // 下面就是自己對數組進行操作就行了 const list = res.map(item => { return { keyword: item.keyword, weight: item.weight } }); wordObj.setKeys([...wordObj.keys, ...list]); }; reader.readAsArrayBuffer(f); // 讀取數據 };