html使用exceljs 导出excel
2021-05-26 本文已影响0人
zt_sole
记录一下前端html使用excel 导出excel 学习的demo
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>html exceljs 数据表格导出</title>
<script src="js/vue.js" type="text/javascript" charset="utf-8"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-polyfill/6.26.0/polyfill.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/exceljs/4.2.1/exceljs.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/FileSaver.js/2.0.5/FileSaver.min.js"></script>
</head>
<body>
<button onclick="exportExcel()">导出excel</button>
<script>
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');
});
}
</script>
</body>
</html>
image.png