最近在使用electon写一个桌面程序,需要对数据进行excel导出操作,这里选择使用 exceljs
来完成这个功能,下面是exceljs导出功能的简单实现。
下载 exceljs
yarn add exceljs
引入 exceljs
const ExcelJS = require('exceljs');
创建工作簿并设置工作簿属性
const workbook = new ExcelJS.Workbook();
workbook.creator = 'Me';
workbook.lastModifiedBy = 'Her';
workbook.created = new Date(1985, 8, 30);
workbook.modified = new Date();
workbook.lastPrinted = new Date(2016, 9, 27);
添加工作表
const sheet = workbook.addWorksheet('My Sheet');
工作表就是装载excel表里面数据的容器
往工作表添加数据
设置表头
worksheet.columns = [
{ header: 'Id', key: 'id', width: 10 },
{ header: 'Name', key: 'name', width: 32 },
{ header: 'D.O.B.', key: 'DOB', width: 10 }
];
添加数据
const data = [
[1, 'electron','DOB']
[2, 'exceljs', 'DOB]
];
worksheet.addRows(data);
导出xlsx文件
await workbook.xlsx.writeFile(filename);
所有代码
const ExcelJS = require('exceljs');
const excelExport = async () => {
const workbook = new ExcelJS.Workbook();
workbook.creator = 'Me';
workbook.lastModifiedBy = 'Her';
workbook.created = new Date(1985, 8, 30);
workbook.modified = new Date();
workbook.lastPrinted = new Date(2016, 9, 27);
const worksheet = workbook.addWorksheet('My Sheet');
worksheet.columns = [
{ header: 'Id', key: 'id', width: 10 },
{ header: 'Name', key: 'name', width: 32 },
{ header: 'D.O.B.', key: 'DOB', width: 10 }
];
const data = [
[1, 'electron','DOB'],
[2, 'exceljs', 'DOB']
];
worksheet.addRows(data);
await workbook.xlsx.writeFile(fileName);
}
excelExport();