记录一下前端html使用excel 导出excel 学习的demo
html exceljs 数据表格导出导出excel
function exportExcel(){
// 创建一个workbook
var workbook = new ExcelJS.Workbook();
// workbook 添加一个 123 标签的sheet
var worksheet = workbook.addWorksheet("123");
// 设置sheet数据中的列名
worksheet.columns = [{
header: 'id',
key: 'id'
},
{
header: '姓名',
key: 'name'
},
{
header: '电话',
key: 'phone'
}
];
// 设置数据(可以通过后台获取、获取已经存在的数据)
var data = [{
id: 1,
name: '张三',
phone: '1234567890'
},
{
id: 2,
name: '李四',
phone: '123'
}];
// 开始添加数据
/* for (let i in data) {
worksheet.addRow(data[i]).commit();
} */
worksheet.addRows(data);
const EXCEL_TYPE = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8';
// 下载excel
workbook.xlsx.writeBuffer().then((data) => {
const blob = new Blob([data], {
type: EXCEL_TYPE
});
saveAs(blob, 'download.xlsx');
});
}
image.png