const fs = require('fs')
const Excel = require('exceljs')
const workbook = new Excel.Workbook()
workbook.creator = 'test'
workbook.lastModifiedBy = 'test'
workbook.created = new Date()
workbook.modified = new Date()
let sheet = workbook.addWorksheet('2018-10报表')
// # Add column headers and define column keys and widths
// 添加表头
sheet.getRow(1).values = ['种类', '销量', , , , '店铺'];
sheet.getRow(2).values = ['', '2018-05', '2018-06', '2018-07', '2018-08', '店铺'];
sheet.getRow(4).values = ["5565"];//添加为表头数据会在它的下一行显示
// 添加数据项定义,与之前不同的是,此时去除header字段
//columns不能用push直接添加数据需要先动态创建好数据然后sheet.columns=arr;格式如下
sheet.columns = [
{key: 'store', width: 30},
{key: 'category', width: 30},
{key: '2018-08', width: 30},
{key: '2018-05', width: 30},
{key: '2018-06', width: 30},
{key: '2018-07', width: 30},
]
const data = [{
category: '衣服',
'2018-05': 300,
'2018-06': 230,
'2018-07': 730,
'2018-08': 630,
'2018-066': 782,
'store': '王小二旗舰店'
}, {
category: '零食',
'2018-05': 672,
'2018-06': 826,
'2018-07': 302,
'2018-08': 389,
'store': '吃吃货'
}]
sheet.addRows(data)
// 合并单元格
// sheet.mergeCells(`B1:E1`)
// sheet.mergeCells('A1:A2')
// sheet.mergeCells('F1:F2')
//
// sheet.mergeCells(1,1,2,1);//第1行 第2列 合并到第1行的第5列
sheet.mergeCells(1, 2, 1, 5);//第1行 第2列 合并到第1行的第5列
sheet.mergeCells(4, 1, 5, 1);//第1行 第2列 合并到第1行的第5列
// sheet.mergeCells(1,2,1,5);//第1行 第2列 合并到第1行的第5列
sheet.getCell(1, 2, 1, 5).fill = {
// 模式
type: 'pattern',
// 填充
pattern: 'solid',
// 背景色
fgColor: {
argb: '333333'
}
};
// 设置每一列样式
const row = sheet.getRow(1)
row.eachCell((cell, rowNumber) => {
sheet.getColumn(rowNumber).alignment = {vertical: 'middle', horizontal: 'center'}
sheet.getColumn(rowNumber).font = {size: 14, family: 2}
})
// # Add an array of rows
sheet.addRows([]);//此处添加一个空的数组
(async function () {
return await workbook.xlsx.writeFile('用户报表.xlsx').then(async () => {
console.log(this)
// this.ctx.attachment(`用户报表.xlsx`)
// this.ctx.type = '.xlsx'
// this.ctx.body = fs.readFileSync(filePath)
}, function (err) {
console.log(err)
})
})()
exceljs node 生成可合并单元格的excel
最新推荐文章于 2024-07-30 11:29:23 发布