引入所需依赖
import Excel from 'exceljs';import {saveAs} from 'file-saver';
创立工作簿并写入内容
const workbook = new Excel.Workbook();const worksheet = workbook.addWorksheet('My Sheet');worksheet.columns = [ { header: '编号', key: 'id', width: 10 }, { header: '姓名', key: 'name', width: 32 }, { header: '年龄', key: 'age', width: 10 }];var rows = [ ['001','MIKA','23'], // row by array {id:'002', name: 'Kaz', age:'24'}];worksheet.addRows(rows);
利用 file-saver的saveAs保留至本地
const fileType="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.ms-excel"workbook.xlsx.writeBuffer().then(data=>{ const blob = new Blob([data],{type:fileType}); saveAs(blob,'test.xlsx');})
进行到这一步,基本上就曾经实现了保留excel表格到本地的需要。
参考:exceljs官网文档