使用xlsx-populate
1.安装
npm i xlsx --save
npm i xlsx-populate --save
2.新建js文件,内容如下
import XlsxPopulate from "xlsx-populate";
import { saveAs } from "file-saver";
export async function exportExcel(filename, data) {
const workbook = await XlsxPopulate.fromBlankAsync();
const sheet = workbook.sheet(0);
// 设置单元格样式
sheet.range(`A2:${String.fromCharCode(64 + data[0].length)}${data.length + 1}`).style({ horizontalAlignment: "center" });
// 填充数据
sheet.cell("A1").value(data);
// 设置表头样式
for (let i = 1; i <= data[0].length; i++) {
const cell = sheet.cell(1, i);
if (cell.value()) {
cell.style({ fill: "d0cece", horizontalAlignment: "center" });
}
}
// 设置列宽
for (let i = 1; i <= data[0].length; i++) {
sheet.column(i).width(17);
}
// 设置外边框
const range = sheet.range(`A1:${String.fromCharCode(64 + data[0].length)}${data.length + 1}`);
range.style({ border: true });
// 设置内边框
const innerRange = sheet.range(`B2:${String.fromCharCode(64 + data[0].length - 1)}${data.length}`);
innerRange.style({ border: true });
// 生成Excel文件的二进制数据
const excelData = await workbook.outputAsync();
// 创建Blob对象
const blob = new Blob([excelData], { type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" });
// 使用FileSaver.js保存文件
saveAs(blob, filename + ".xlsx");
}
3.在页面中引入使用
import { exportExcel } from "#/api/gkzbfw/excelUtil"; 引入//
export default {
data() {
return {
tableData:[ ['姓名','年龄','性别'],
['张三','12','男'],
['张三1','112','男'],
['张三2','1212','女']
]
}
},
methods:{
exportData(){
//导出
exportExcel('表格',this.tableData)
}
}
}
4.结果如图