|
@@ -57,6 +57,42 @@ const openDownloadDialog = (blob, fileName) => {
|
57
|
57
|
}
|
58
|
58
|
aLink.dispatchEvent(event);
|
59
|
59
|
};
|
|
60
|
+// 列自适应宽度
|
|
61
|
+const setColFitWidth = (tableData, headerList, sheet) => {
|
|
62
|
+ function getCellWidth(value) {
|
|
63
|
+ // 判断是否为null或undefined
|
|
64
|
+ if (!value) {
|
|
65
|
+ return 10;
|
|
66
|
+ } else if (/.*[\u4e00-\u9fa5]+.*$/.test(value)) {
|
|
67
|
+ // 判断是否包含中文
|
|
68
|
+ return value.toString().length * 2.1;
|
|
69
|
+ } else {
|
|
70
|
+ return value.toString().length * 1.1;
|
|
71
|
+ }
|
|
72
|
+ }
|
|
73
|
+ let colWidths = []; // 所有列的名称数组
|
|
74
|
+ // 计算每一列的所有单元格宽度
|
|
75
|
+ // 先遍历行
|
|
76
|
+ tableData.forEach((row) => {
|
|
77
|
+ // 遍历列
|
|
78
|
+ for (const key in row) {
|
|
79
|
+ let index = headerList.findIndex((v) => v === key);
|
|
80
|
+ if (!colWidths[index]) {
|
|
81
|
+ colWidths[index] = [];
|
|
82
|
+ }
|
|
83
|
+ colWidths[index].push(getCellWidth(row[key]));
|
|
84
|
+ }
|
|
85
|
+ });
|
|
86
|
+ sheet["!cols"] = [];
|
|
87
|
+ // 每一列取最大值最为列宽
|
|
88
|
+ colWidths.forEach((widths, index) => {
|
|
89
|
+ // 计算列头的宽度
|
|
90
|
+ widths.push(getCellWidth(headerList[index]));
|
|
91
|
+ // 设置最大值为列宽
|
|
92
|
+ sheet["!cols"].push({ wch: Math.max(...widths, 10) });
|
|
93
|
+ });
|
|
94
|
+ return sheet;
|
|
95
|
+};
|
60
|
96
|
/**
|
61
|
97
|
* 导出Excel表格
|
62
|
98
|
* @param sheetListInfo sheet列表信息 [{list:数组数据, name: sheet名称}]
|
|
@@ -65,12 +101,14 @@ const openDownloadDialog = (blob, fileName) => {
|
65
|
101
|
export const exportToExcel = (sheetListInfo, excelName) => {
|
66
|
102
|
const wb = XLSX2.utils.book_new();
|
67
|
103
|
sheetListInfo.forEach((sheetItem, sheetIndex) => {
|
|
104
|
+ let headerList = [];
|
68
|
105
|
sheetItem.list.forEach((item) => {
|
69
|
106
|
for (const key in item) {
|
|
107
|
+ headerList.push(key);
|
70
|
108
|
item[key] = item[key] || "";
|
71
|
109
|
}
|
72
|
110
|
});
|
73
|
|
- const sheet = XLSX2.utils.json_to_sheet(sheetItem.list);
|
|
111
|
+ let sheet = XLSX2.utils.json_to_sheet(sheetItem.list);
|
74
|
112
|
// 设置每个单元格的样式
|
75
|
113
|
let range = XLSX.utils.decode_range(sheet["!ref"]);
|
76
|
114
|
for (let R = range.s.r; R <= range.e.r; ++R) {
|
|
@@ -83,6 +121,7 @@ export const exportToExcel = (sheetListInfo, excelName) => {
|
83
|
121
|
}
|
84
|
122
|
}
|
85
|
123
|
}
|
|
124
|
+ sheet = setColFitWidth(sheetItem.list, headerList, sheet);
|
86
|
125
|
XLSX2.utils.book_append_sheet(
|
87
|
126
|
wb,
|
88
|
127
|
sheet,
|