匯入 Excel - Sheets in VueJS Sites

前言

SheetJS 是一個 JavaScript 函式庫,用於從表格中讀取和寫入資料。

下載

1
npm i xlsx

GitHub
官網 - SheetJS CE Docs - Vue

匯出資料 - Updating State

1
2
3
4
5
6
<div class="importBtn__wrap ml-12px">
<div class="relative w-96px">
<el-button color="#F9EEA4">匯入名冊</el-button>
<input @click="clearFile" @change="handleUpload" type="file" accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" ref="uploadFile" class="absolute left-0 top-0 h-full w-full opacity-0"/>
</div>
</div>
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
/** @const {object} 取得DOM元素 */
const uploadFile = ref(null);

/** @const {array} 匯入清單 */
const importList = ref([]);

/** @func 讀取檔案內容 */
async function getWorkbookFromFile(excelFile) {
return new Promise((resolve) => {
const reader = new FileReader();
reader.onload = (event) => {
const data = event.target.result;
/* 將檔案讀取 */
const workbook = XLSX.read(data, { type: 'binary' });
/** 這個是excel 下方可以新增很多 的 工作表(workbook) */
const rowObj = XLSX.utils.sheet_to_json(workbook.Sheets['工作表1']);
/** 測試: 讀取工作表名稱 */
// console.log(workbook.SheetNames);
resolve(rowObj);
};

/* FileReader 執行動作 將傳入的 File讀取 */
reader.readAsBinaryString(excelFile);
});
}

/** @func 檔案上傳 change 事件 */
async function handleUpload() {
const file = uploadFile.value.files[0];
const workbook = await getWorkbookFromFile(file);
importList.value = workbook.map((item) => reverseObjKey(item));
}

/** @func 清空指定的DOM */
function clearFile(e) {
e.target.value = '';
}

常見content-type對應表

常使用的幾種

種類 檔案副檔名 Content-Type(Mime-Type)
2003 Excel .xls application/vnd.ms-excel
2010 Excel .xlsx application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
文字檔案 .txt text/plain
圖片 .png/.jpg/.gif image/*
頁面 .htm/.html text/html
影片 .avi/ .mpg/ .mpeg/ .mp4 video/*
音訊 .mp3/ .wav/ audio/*
PDF .pdf application/pdf

參考資料

常見content-type對應表

JS - SheetJS