前端表格数据下载xlsx

前端表格数据下载 xlsx

1、后端返回数据,前端进行下载,通过exceljs.min.js插件进行下载
2、引入组件 import ExcelJS from './exceljs.min.js'

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
 //下载配置
downConfig() {
//前端下载表格数据
let workbook = new ExcelJS.Workbook();
let worksheet = workbook.addWorksheet("Sheet1");
//获取表格
let table = document.getElementById("tableId");
let rows = table.rows;
// 遍历表格行和列,将数据添加到工作表中
for (let i = 0; i < rows.length; i++) {
let rowData = [];
let cells = rows[i].cells;
for (let j = 0; j < cells.length; j++) {
let cell = worksheet.getCell(`${String.fromCharCode(65 + j)}${i + 1}`);
cell.value = cells[j].innerText;
// 设置单元格边框样式
cell.border = {
top: { style: "thin" },
left: { style: "thin" },
bottom: { style: "thin" },
right: { style: "thin" }
};
// 设置表头单元格(A1到D1)的背景颜色
if (i === 0 && j >= 0 && j <= 3) {
cell.fill = {
type: "pattern",
pattern: "solid",
fgColor: { argb: "c1d5f1" }, // 设置为蓝色,可以根据需要修改颜色值
};
}
if (j === 0) {
cell.fill = {
type: "pattern",
pattern: "solid",
fgColor: { argb: "c1d5f1" }, // 设置为蓝色,可以根据需要修改颜色值
};
}
}
worksheet.addRow(rowData);
}
worksheet.columns.forEach(function (column) {
let maxLength = 0;
column.eachCell({ includeEmpty: true }, function (cell) {
let length = cell.value ? cell.value.toString().length : 0;
maxLength = Math.max(maxLength, length);
});
column.width = maxLength < 12 ? 12 : maxLength + 2; // 设置列宽度,加上额外的空隙
});

// 创建下载链接
workbook.xlsx.writeBuffer().then(function (buffer) {
let blob = new Blob([buffer], { type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" });
let downloadLink = document.createElement("a");
downloadLink.href = URL.createObjectURL(blob);
downloadLink.download = "配置预览.xlsx";
// 添加下载链接到页面
document.body.appendChild(downloadLink);
// 模拟点击下载链接
downloadLink.click();
// 清理下载链接
document.body.removeChild(downloadLink);
});
},

前端表格数据下载xlsx
http://example.com/2023/06/20/前端表格数据下载xlsx/
作者
dinghw
发布于
2023年6月20日
许可协议