|
@@ -0,0 +1,74 @@
|
|
1
|
+import XLSX2 from "xlsx";
|
|
2
|
+import XLSX from "xlsx-style";
|
|
3
|
+const workbook2blob = (workbook) => {
|
|
4
|
+ // 生成excel的配置项
|
|
5
|
+ let wopts = {
|
|
6
|
+ // 要生成的文件类型
|
|
7
|
+ bookType: "xlsx",
|
|
8
|
+ // 是否生成Shared String Table,官方解释是,如果开启生成速度会下降,但在低版本IOS设备上有更好的兼容性
|
|
9
|
+ bookSST: false,
|
|
10
|
+ type: "binary"
|
|
11
|
+ };
|
|
12
|
+ let wbout = XLSX.write(workbook, wopts);
|
|
13
|
+ // 将字符串转ArrayBuffer
|
|
14
|
+ function s2ab(s) {
|
|
15
|
+ let buf = new ArrayBuffer(s.length);
|
|
16
|
+ let view = new Uint8Array(buf);
|
|
17
|
+ for (let i = 0; i !== s.length; ++i) view[i] = s.charCodeAt(i) & 0xff;
|
|
18
|
+ return buf;
|
|
19
|
+ }
|
|
20
|
+ let buf = s2ab(wbout);
|
|
21
|
+ let blob = new Blob([buf], {
|
|
22
|
+ type: "application/octet-stream"
|
|
23
|
+ });
|
|
24
|
+ return blob;
|
|
25
|
+};
|
|
26
|
+// 将blob对象 创建bloburl,然后用a标签实现弹出下载框
|
|
27
|
+const openDownloadDialog = (blob, fileName) => {
|
|
28
|
+ if (typeof blob === "object" && blob instanceof Blob) {
|
|
29
|
+ blob = URL.createObjectURL(blob); // 创建blob地址
|
|
30
|
+ }
|
|
31
|
+ let aLink = document.createElement("a");
|
|
32
|
+ aLink.href = blob;
|
|
33
|
+ // HTML5新增的属性,指定保存文件名,可以不要后缀,注意,有时候 file:///模式下不会生效
|
|
34
|
+ aLink.download = fileName || "";
|
|
35
|
+ let event;
|
|
36
|
+ if (window.MouseEvent) event = new MouseEvent("click");
|
|
37
|
+ // 移动端
|
|
38
|
+ else {
|
|
39
|
+ event = document.createEvent("MouseEvents");
|
|
40
|
+ event.initMouseEvent(
|
|
41
|
+ "click",
|
|
42
|
+ true,
|
|
43
|
+ false,
|
|
44
|
+ window,
|
|
45
|
+ 0,
|
|
46
|
+ 0,
|
|
47
|
+ 0,
|
|
48
|
+ 0,
|
|
49
|
+ 0,
|
|
50
|
+ false,
|
|
51
|
+ false,
|
|
52
|
+ false,
|
|
53
|
+ false,
|
|
54
|
+ 0,
|
|
55
|
+ null
|
|
56
|
+ );
|
|
57
|
+ }
|
|
58
|
+ aLink.dispatchEvent(event);
|
|
59
|
+};
|
|
60
|
+/**
|
|
61
|
+ * 导出Excel表格
|
|
62
|
+ * @param sheetListInfo {list:数组数据, name: sheet名称}
|
|
63
|
+ * @param excelName Excel表格名称
|
|
64
|
+ */
|
|
65
|
+export const exportToExcel = (sheetListInfo, excelName) => {
|
|
66
|
+ const wb = XLSX2.utils.book_new();
|
|
67
|
+ for (const sheetItem of sheetListInfo) {
|
|
68
|
+ const sheet = XLSX2.utils.json_to_sheet(sheetItem.list);
|
|
69
|
+ XLSX2.utils.book_append_sheet(wb, sheet, sheetItem.name);
|
|
70
|
+ }
|
|
71
|
+ const workbookBlob = workbook2blob(wb);
|
|
72
|
+ // 导出最后的总表
|
|
73
|
+ openDownloadDialog(workbookBlob, excelName + ".xlsx");
|
|
74
|
+};
|