import FileSaver from "file-saver";
import XLSXStyle from "xlsx-style";
import XLSX from "xlsx";
export function exportExcel(data, name, merges, zishu, save = true) {
return new Promise((resolve) => {
let index = 0;
// 合并单元格 s:开始位置 e:结束位置 r:行 c:列
// const datamerges = [
// // 实际情况根据业务需求进行
// //{ s: { c: 0, r: 0 }, e: { c: merges, r: 0 } },
// { s: { c: 0, r: data.length + 1 }, e: { c: 0, r: data.length + 1 } },
// ];
let ws_data = [["标题", "2", "q", "d", "c", "q", "z", "e", "r"]];
for (let i = 0; i < 10; i++) {
ws_data.push(["1", "2", "", "", "", "", "", "", "8"]);
}
var worksheet1 = XLSX.utils.aoa_to_sheet(ws_data);
//worksheet1["A1"].v = "合并值";
//worksheet1["!merges"] = datamerges;
// worksheet1.A1 = {
// t: "s",
// v: name,
// };
for (const key in worksheet1) {
index++;
// 前两行高度为45,其后行高为25
// 所有单元格居中
if (
key !== "!cols" &&
key !== "!merges" &&
key !== "!ref" &&
key !== "!rows" &&
) {
worksheet1[key].s = {
font: {
// bold: true,
sz: 12,
},
alignment: {
//horizontal: "center",
vertical: "center",
},
};
}
// A1单元格加粗居中
// if (key === "A1") {
// worksheet1[key].s = {
// font: {
// bold: true,
// sz: 20,
// },
// alignment: {
// horizontal: "center",
// vertical: "center",
// },
// };
// }
// 表头加粗居中
// if (key.replace(/[^0-9]/gi, "") === "2") {
// worksheet1[key].s = {
// font: {
// bold: true,
// },
// alignment: {
// horizontal: "center",
// vertical: "center",
// },
// };
// }
}
worksheet1["!cols"] = [
{ wch: 10 },
{ wch: 20 },
{ wch: 30 },
]; // 列宽
worksheet1["!rows"] = [{ hpx: 1 }, { hpx: 40 }]; // 行高
const sheetNames = Object.keys({ 总表: worksheet1 });
const workbook = {
SheetNames: sheetNames, // 保存的工作表名
Sheets: { 总表: worksheet1 }, // 与表名对应的表数据
};
// // excel的配置项
const wopts = {
bookType: "xlsx", // 生成的文件类型
bookSST: false, // 是否生成Shared String Table,官方解释是,如果开启生成速度会下降,但在低版本IOS设备上有更好的兼容性
type: "binary",
};
// attempts to write the workbook
// const wbout = styleXLSX.write(workbook, wopts)
const wbout = XLSXStyle.write(workbook, wopts);
try {
wbout.then((res) => {
const wbBlob = new Blob([s2ab(res)], {
type: "application/octet-stream",
});
if (save) {
saveAs(wbBlob, name + "." + "xlsx");
} else {
resolve(wbBlob);
}
});
} catch (error) {
const wbBlob = new Blob([s2ab(wbout)], {
type: "application/octet-stream",
});
if (save) {
saveAs(wbBlob, name + "." + "xlsx");
} else {
resolve(wbBlob);
}
}
});
}