Files
mosr-web/src/utils/export-excel.js

118 lines
3.4 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import {utils} from "xlsx";
import FileSaver from 'file-saver'
import XLSX from "xlsx-style-vite";
/**
* 导出excel
* @param $table 表格html dom元素
* @param columnLength 列长度
* @param excelName 导出文件名称
* @param bigWidthIndex 更宽列的索引
*/
export function exportExcel($table, columnLength, excelName, bigWidthIndex) {
//从el-table表生成工作簿对象
//使用原始的格式,保留表格中的格式如%、小数末尾的0等
let workbook = utils.table_to_book($table, {
raw: true
});
//列宽需要导出的表格有多少列这里的i就小于多少
for (let i = 1; i < columnLength; i++) {
if (i === bigWidthIndex) {
workbook.Sheets.Sheet1["!cols"].push({wpx: 300});
}
workbook.Sheets.Sheet1["!cols"].push({wpx: 100});
}
//设置单元格样式
for (const key in workbook.Sheets.Sheet1) {
if (
key !== "!cols" &&
key !== "!fullref" &&
key !== "!merges" &&
key !== "!ref" &&
key !== "!rows"
) {
//这里的s就是具体的样式如果想设置不一样的样式可以看xlsx-style文档
workbook.Sheets.Sheet1[key].s = {
//边框
border: {
top: {style: "thin"},
bottom: {style: "thin"},
left: {style: "thin",},
right: {style: "thin",}
},
//对齐
alignment: {
horizontal: "center",
vertical: "center",
wrapText: true
}
};
}
}
//修改合并单元格样式
let arr = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N",
"O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"];
//由于导出时合并单元格只识别左上角的单元格,合并单元格中其他单元格
//并不会存在,所以需要识别合并单元格中除左上角单元格外的单元格并添加
//带样式的单元格到其中不理解可以看四中的第2点。
try {
for (let item of workbook.Sheets.Sheet1["!merges"]) {
let style = {
border: {
top: {style: "thin"},
bottom: {style: "thin"},
left: {style: "thin",},
right: {style: "thin",}
},
alignment: {
horizontal: "center",
vertical: "center",
wrapText: true
}
};
let merge_s = {t: "s", v: "", s: style};
if (item.s.c === item.e.c) {
//纵向合并其中c为字母r为数字
let star = item.s.r;
let end = item.e.r;
for (let i = star + 1; i <= end; i++) {
workbook.Sheets.Sheet1[arr[item.s.c] + (i + 1)] = merge_s;
}
} else {
//横向合并
let star = item.s.c;
let end = item.e.c;
for (let i = star; i < end; i++) {
workbook.Sheets.Sheet1[arr[i + 1] + Number(item.s.r + 1)] = merge_s;
}
}
}
} catch (e) {
}
//将表格数据中的字符串转ArrayBuffer
function s2ab(s) {
let buf = new ArrayBuffer(s.length);
let view = new Uint8Array(buf);
for (let i = 0; i !== s.length; ++i) view[i] = s.charCodeAt(i) & 0xff;
return buf;
}
//这里的属性可以参考xlsx-style文档
let wbout = XLSX.write(workbook, {
bookType: "xlsx",
bookSST: false,
type: "binary"
});
try {
FileSaver.saveAs(
new Blob([s2ab(wbout)], {type: "application/octet-stream"}),
`${excelName}.xlsx`
);
} catch (e) {
if (typeof console !== "undefined") console.log(e, wbout);
}
}