First install xlsx
npm install xlsx
Project introduced
import XLSX from 'xlsx';
Upload component, because too lazy to write style, antd the Upload component used here, use <input type = "file" /> is also possible.
Use customRequest custom upload
<Upload name="file" accept=".xls,.xlsx" showUploadList={false} customRequest={upload} > <span className={cns(style.btn, style.import)}> <img src={importPNG}/> <span>导入数据</span> </span> </Upload>
Core code, parsing excel
Upload = const (E) => { const F = e.file; const Reader = new new FileReader (); // read the data using FileReader reader.onload = function (E) {// read the data after completion callback Data const = new new Uint8Array (e.target.result); const Workbook = XLSX.read (Data, {type: 'Array'}); // Workbook is parsed to return the object to excel xlsx const firstSheetName = workbook.SheetNames [0 ]; // get the first sheet name const Worksheet = workbook.Sheets [firstSheetName]; // get the contents of the first sheet XLSX.utils.sheet_to_json RES = const (Worksheet); // use the method of converting content utils in the array for ease of use // The following array is their operation on the line const = List Item res.map (=> { return { keyword: item.keyword, weight: item.weight } }); wordObj.setKeys ([... wordObj.keys, ... List]); }; reader.readAsArrayBuffer (F); // read data };