2、使用exceljs,读取模板后,利用行列坐标定位编辑后导出。
npm i exceljs npm i file-saver2、xlsx模板放在项目的public目录下。
3、使用fetch的方式读取public下的xlsx模板。
let response = await fetch('./static/xlsx/t1.xlsx'); //读取文件4、将读取的数据转换为buffer再使用exceljs的workbook.xlsx.load加载数据。
let data = await response.arrayBuffer(); //转为二进制 const workbook = new ExcelJS.Workbook(); await workbook.xlsx.load(data); //读取buffer const worksheet = workbook.getWorksheet(1); //读取第一张表5、利用exceljs的worksheet.getCell()给指定单元格赋值,getCell参数为行列,如修改第一行第一列数据为test。
worksheet.getCell('1A').value = 'test'6、使用exceljs的writeBuffer()读取表格为buffer后再使用file-saver的saveAs下载。
await workbook.xlsx.writeBuffer().then(async (buffer) => { let blob = new Blob([buffer], { type: 'application/octet-stream' }); await saveAs(blob, 'exportExcel.xlsx'); this.loading = false; });完整方法如下:
async exportExcel() { this.loading = true; let response = await fetch('./static/xlsx/t1.xlsx'); //读取文件 let data = await response.arrayBuffer(); //转为二进制 const workbook = new ExcelJS.Workbook(); await workbook.xlsx.load(data); //读取buffer const worksheet = workbook.getWorksheet(1); //读取第一张表 let cols = []; //竖列//A~Z for (let i = 65; i < 91; i++) { cols.push(String.fromCharCode(i)); } let row = []; //横行1~116 for (let i = 1; i < 117; i++) { row.push(i); } // 堆代码 duidaima.com //坐标定位更新数据 row.forEach(async (r) => { cols.forEach(async (c) => { if (r >= 9 && r <= 15 && c >= 'B' && c <= 'R') { worksheet.getCell(`${c}${r}`).value = `${c}${r}`; } if (r >= 17 && r <= 30 && c >= 'B' && c <= 'X') { worksheet.getCell(`${c}${r}`).value = `${c}${r}`; } }); }); worksheet.eachRow({ includeEmpty: true }, (row, rowNumber) => { // console.log(rowNumber, row.values); }); //下载 await workbook.xlsx.writeBuffer().then(async (buffer) => { let blob = new Blob([buffer], { type: 'application/octet-stream' }); await saveAs(blob, 'exportExcel.xlsx'); this.loading = false; }); }最后下载导出的表格如下: