1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67
| import saveAs from 'file-saver'; import ExcelJS from 'exceljs'; import dayjs from 'dayjs'; import * as XLSX from 'xlsx'; import { Message } from '@arco-design/web-vue'; import { FileItem } from '@arco-design/web-vue/es/upload/interfaces'; export interface DownloadExcelPrams { columns: { title: string, key: string }[]; rows: object[]; name: string }
export function downloadExcel({ columns, rows, name = '未命名文件' }: DownloadExcelPrams) { console.log(dayjs().format('YYYY-MM-DD HH时mm分')) const workbook = new ExcelJS.Workbook(); workbook.creator = 'Start-front'; workbook.lastModifiedBy = 'Start-front'; workbook.created = new Date(1985, 8, 30); workbook.modified = new Date(); workbook.lastPrinted = new Date(2016, 9, 27);
const sheet1 = workbook.addWorksheet(name); sheet1.columns = columns.map(item => ({ header: item.title, key: item.key, width: 20 })); rows.map(item => sheet1.addRow(item)); workbook.xlsx.writeBuffer().then(buffer => { console.log(buffer) saveAs( new Blob([buffer], { type: 'application/octet-stream' }), `${name}(${dayjs().format('YYYY年MM月DD日HH时mm分')}导出).xlsx` ); }); };
export function readExcle(fileItem:FileItem) { console.log('读取文件...',fileItem); return new Promise((resove,reject)=>{ try { let workbook:XLSX.Sheet; const reader = new FileReader(); reader.readAsBinaryString(fileItem.file as File); reader.onload = function(ev){ const data = ev.target?.result; workbook = XLSX.read(data, {type: 'binary'}); const sheetNames = workbook.SheetNames; sheetNames.forEach((name:string) => { var worksheet = workbook.Sheets[name]; let jsonres = XLSX.utils.sheet_to_json(worksheet); resove(jsonres) }); } } catch (error) { Message.error('读取失败,请选择正确文件'); reject(error); } }) }
|