Vite 導出Excel 使用SheetJs Part 1 (語法糖)

開發EIP系統時需要將數據導出Excel ,所以使用了 Sheetjs套件,
在剛開始的測試階段全部都定義全部都導出設定,

一 安裝Sheetjs
二 引入 xlsx
三 寫導出功能

遍歷=>使用函式utils.json_to_sheet(數據)=>utils.book_new() =>附加 utils.book_append_sheet(workbook, worksheet, "Dates")=>寫檔XLSX writeFileXLSX(workbook, "出勤列表.xlsx")就導出了出勤列表.xlsx

四 點擊綁定@click="exportExcel"

sheetjs官網

一 Vite 安裝 Sheetjs

1
2
3
4
5
6
7
// npm
npm i --save https://cdn.sheetjs.com/xlsx-0.20.0/xlsx-0.20.0.tgz
// pnpm
pnpm install https://cdn.sheetjs.com/xlsx-0.20.0/xlsx-0.20.0.tgz
// yarn
yarn add https://cdn.sheetjs.com/xlsx-0.20.0/xlsx-0.20.0.tgz

二 在使用中的組件引入 xlsx
三 寫導出功能exportExcel 函式 參閱Sheet Export Tutorial
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
<template>
<!----點擊導出Excel-->
<el-button @click="exportExcel" type="primary">導出Excel</el-button>
</template>

<script setup lang="ts">
import { ref, onMounted } from "vue";
import { utils, writeFileXLSX } from "xlsx"; // 引入導出 Excel 套件
interface listType {
UID?: string;
version?: string;
category?: string;
comment?: string;
descriptionFilterHtml?: string;
editModifyDate?: string;
hitRate?: number;
imageUrl?: string;
masterUnit?: object;
title?: string | any;
sourceWebName?: string | any;
startDate?: string | any;
discountInfo?: string | any;
}
// 輸出 Excel的內容
const excelXlsContent = ref<any[]>([]);
// 三 寫導出功能 輸出 現有表格數據
const exportExcel = () => {
// 設定Excel Header
excelXlsContent.value= lists.value.map((row: listType, index:number) => (
{
'項目': Number(index + 1),
'主題': row.title,
'來源': row.sourceWebName,
'開始': row.startDate,
'地點': row.discountInfo,
}
));

const worksheet = utils.json_to_sheet(excelXlsContent.value);
const workbook = utils.book_new();
utils.book_append_sheet(workbook, worksheet, "Dates");
writeFileXLSX(workbook, "出勤列表.xlsx");
}
const getItems = async () => {
try {
const api = 'https://cloud.culture.tw/frontsite/trans/SearchShowAction.do?method=doFindTypeJ&category=200';
const res = await axios.get(api);
console.log('culture', res.data, typeof res.data[0].masterUnit
);
lists.value = res.data;
}
catch (err) {
console.log('err', err);
}
}
onMounted(() => {
getItems()
})
</script>

讓使用者可以選擇要輸出的項目

要有表單讓使用選擇
使用跳出框,下期補件