使用xlsx-populate库为XLSX.utils.sheet_add_aoa单元格添加背景色
要给XLSX.utils.sheet_add_aoa函数添加背景色,可以使用'xlsx-populate'库来实现。以下是一个示例代码:
const XlsxPopulate = require('xlsx-populate');
const data = [
['Name', 'Age', 'Email'],
['John', 30, 'john@example.com'],
['Jane', 25, 'jane@example.com'],
['Mike', 35, 'mike@example.com'],
];
XlsxPopulate.fromBlankAsync()
.then(workbook => {
const sheet = workbook.sheet(0);
sheet.cell('A1').style({
fill: {
type: 'pattern',
patternType: 'solid',
fgColor: 'FF0000FF' // 设置背景色为蓝色
}
});
sheet.cell('B1').style({
fill: {
type: 'pattern',
patternType: 'solid',
fgColor: 'FFFF0000' // 设置背景色为红色
}
});
sheet.cell('C1').style({
fill: {
type: 'pattern',
patternType: 'solid',
fgColor: 'FF00FF00' // 设置背景色为绿色
}
});
sheet.cell('A1:C1').style({ bold: true });
sheet.cell('A2:C4').value(data);
return workbook.toFileAsync('output.xlsx');
})
.then(() => {
console.log('Excel file created successfully.');
})
.catch(err => {
console.log('Error:', err);
});
此示例中,我们使用'xlsx-populate'库创建一个新的Excel工作簿,并在第一个工作表中添加数据。然后,我们使用.sheet方法获取工作表对象,使用.cell方法选择要设置背景色的单元格,并使用.style方法设置填充属性以设置背景色。最后,我们使用.value方法将数据添加到工作表中,并使用.toFileAsync方法将工作簿保存为'output.xlsx'文件。
请注意,为了使用此库,您需要在项目中安装'xlsx-populate'依赖项。您可以使用以下命令进行安装:
npm install xlsx-populate
原文地址: https://www.cveoy.top/t/topic/mMLp 著作权归作者所有。请勿转载和采集!