Node.js/javascript 快速导出嵌套列(多表头)的 excel 文件。效果图如下:
1:使用 @zurmokeeper/exceljs,V4.4.1 以上 安装:
npm i @zurmokeeper/exceljs
2: 有一个 worksheet.makeColumns
方法,API 文档: 代码示例:
const ExcelJS = require('@zurmokeeper/exceljs');
(async ()=>{
const test = 'test.xlsx';
const workbook = new ExcelJS.Workbook();
const worksheet = workbook.addWorksheet('Sheet1', {
views: [{state: 'frozen', xSplit: 0, ySplit: 2}], // 冻结第 1 行和第二行
});
// 设置多级表头
worksheet.makeColumns([
{
id: 1,
title: '姓名',
},
{id: 2, title: 'Qwe'},
{id: 3, title: 'Foo'},
{
id: 4,
title: '基础信息',
children: [
{id: 41, title: 'Zoo 1'},
{id: 42, title: 'Zoo 2'},
{id: 44, title: 'Zoo 3'},
],
},
{
id: 5,
title: 'Zoo1',
children: [
{id: 51, title: 'Zoo 51'},
{id: 52, title: 'Zoo 52'},
{id: 54, title: 'Zoo 53'},
],
},
{id: 6, title: 'Foo123213'},
]);
const data = [
[1, 2, 3, null, null, 'DOB'],
[1, 'electron', 'DOB'],
[1, 'electron', 'DOB'],
[1, 'electron', 'DOB'],
[1, 'electron', 'DOB'],
[1, 'electron', 'DOB'],
[1, 'electron', 'DOB'],
[1, 'electron', 'DOB'],
];
worksheet.addRows(data);
worksheet.columns.forEach(function(column) {
column.alignment = {horizontal: 'center', vertical: 'middle'};
});
await workbook.xlsx.writeFile(test);
})()
这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。
V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。
V2EX is a community of developers, designers and creative people.