import * as XLSX from 'xlsx'; export function getXlsxData(file: any) { return new Promise((resolve, reject) => { const fileReader = new FileReader(); fileReader.onload = event => { try { let data:any = []; // 存储获取到的数据 const result = event.target?.result; // 以二进制流方式读取得到整份excel表格对象 const workbook = XLSX.read(result, { type: 'binary' }); // 遍历每张工作表进行读取(这里默认只读取第一张表) for (const sheet in workbook.Sheets) { if (workbook.Sheets.hasOwnProperty(sheet)) { // 利用 sheet_to_json 方法将 excel 转成 json 数据 let sheetJson = XLSX.utils.sheet_to_json(workbook.Sheets[sheet], { defval: '' }) // console.log("sheetJson>>", sheetJson) data = data.concat(sheetJson); // break; // 如果只取第一张表,就取消注释这行 } } resolve(data); } catch (e) { // 这里可以抛出文件类型错误不正确的相关提示 console.log('文件类型不正确'); reject(e); } }; // 以二进制方式打开文件 fileReader.readAsBinaryString(file); }) } export function downloadXlsx(columns: Array<string>, data: Array<any>, fileName: string) { //columns 表头 data文件数据列表 fileName文件名称 let table = []; let obj = {}; columns.forEach((el, index) => { let str = String.fromCharCode(index + 65); obj[str] = el }) table.push(obj) data.forEach((arr) => { let row = {} arr.forEach((el: any, index: number) => { let str = String.fromCharCode(index + 65); row[str] = el }) table.push(row); }); //创建book let wb = XLSX.utils.book_new(); //json转sheet let ws = XLSX.utils.json_to_sheet(table, { header: Object.keys(obj), skipHeader: true }); //设置列宽 ws['!cols'] = (new Array(Object.keys(obj).length)).fill({ 15 }); //sheet写入book XLSX.utils.book_append_sheet(wb, ws, "file"); //输出 let name = fileName || "文件下载" XLSX.writeFile(wb, name + ".xlsx"); } export function formatJson(filterVal: Array<string>, jsonData: Array<any>,) { return jsonData.map((v) => v && Object.keys(v).length ? filterVal.map((j) => v[j] || '') : [] ); }