excel.js
import * as XLSX from 'xlsx';
function autoWidthFunc(ws, data) {
const colWidth = data.map((row) =>
row.map((val) => {
var reg = new RegExp('[\\u4E00-\\u9FFF]+', 'g'); //检测字符串是否包含汉字
if (val === null) {
return { wch: 10 };
} else if (reg.test(val)) {
return { wch: val.toString().length * 2 };
}
return { wch: val.toString().length };
})
);
// start in the first row
const result = colWidth[0];
for (let i = 1; i < colWidth.length; i++) {
for (let j = 0; j < colWidth[i].length; j++) {
if (result[j].wch < colWidth[i][j].wch) {
result[j].wch = colWidth[i][j].wch;
}
}
}
ws['!cols'] = result;
}
function jsonToArray(key, jsonData) {
return jsonData.map((v) =>
key.map((j) => {
return v[j];
})
);
}
const exportArrayToExcel = ({ key, data, title, filename, autoWidth }) => {
const wb = XLSX.utils.book_new();
const arr = jsonToArray(key, data);
arr.unshift(title);
const ws = XLSX.utils.aoa_to_sheet(arr);
if (autoWidth) {
autoWidthFunc(ws, arr);
}
XLSX.utils.book_append_sheet(wb, ws, filename);
XLSX.writeFile(wb, filename + '.xlsx');
};
export default {
exportArrayToExcel,
};
引用
import excel from '@/utils/downloadExcel.js';
// 导出
exportExcel() {
const params = {
title: ['名字', '数量'],
key: ['name', 'count'],
data: this.groupItemList[0].children, // 数据源
autoWidth: true, //autoWidth等于true,那么列的宽度会适应那一列最长的值
filename: this.groupItemList[0].title,
};
excel.exportArrayToExcel(params);
},