excel.js
/*
* @Author: sunqianqian
* @Date: 2023-12-20 09:25:22
* @Description:下載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'); //檢測(cè)字符串是否包含漢字
if (val === null || val === undefined) {
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,
toptitle,
condition,
statistic,
statisticount,
}) => {
const wb = XLSX.utils.book_new();
const arr = jsonToArray(key, data);
arr.unshift(title);
if (statisticount) {
arr.unshift(['', '', '']);
arr.unshift(statisticount);
}
if (statistic) {
arr.unshift(statistic);
}
if (condition) {
arr.unshift(['', '', '']);
arr.unshift(condition);
}
if (toptitle) {
arr.unshift(['', '', '']);
arr.unshift(toptitle);
}
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,
};
引用
只有一組數(shù)據(jù)時(shí)
import excel from '@/utils/downloadExcel.js';
// 導(dǎo)出
exportExcel() {
const params = {
title: ['名字', '數(shù)量'],
key: ['name', 'count'],
data: this.groupItemList[0].children, // 數(shù)據(jù)源
autoWidth: true, //autoWidth等于true,那么列的寬度會(huì)適應(yīng)那一列最長(zhǎng)的值
filename: this.groupItemList[0].title,
};
excel.exportArrayToExcel(params);
},
多種數(shù)據(jù)時(shí)
exportExcel() {
const params = {
// toptitle: ['引證報(bào)告', '', ''],
condition: ['檢索條件:', this.citationSearchTerm, ''],
statistic: ['發(fā)文量', '被引頻次', '篇均被引頻次'],
statisticount: [
this.statisticlist[0].num,
this.statisticlist[1].num,
this.statisticlist[2].num,
],
title: ['引證文獻(xiàn)列表'],
key: ['str'],
data: this.exportListData, // 數(shù)據(jù)源
autoWidth: true, //autoWidth等于true,那么列的寬度會(huì)適應(yīng)那一列最長(zhǎng)的值
filename: '引證報(bào)告',
};
excel.exportArrayToExcel(params);
},