vue3采用xlsx庫實現(xiàn)本地上傳excel文件功能
需求:本地上傳excel 文件,但需要對excel 文件的內(nèi)容進(jìn)行解析,然后展示出來
1. 安裝依賴
首先,確保安裝了 xlsx 庫:
npm install xlsx
2. 創(chuàng)建 Vue 組件
創(chuàng)建一個 Vue 組件(如 ExcelUpload.vue),用于實現(xiàn)文件上傳和解析功能。
組件代碼:
<template>
<div>
<input type="file" class="file-btn hoverPointer" accept=".xls,.xlsx"
@change="changeExcel($event)" />
<div v-if="tableData.length > 0">
<table>
<thead>
<tr>
<th v-for="header in headers" :key="header">{{ header }}</th>
</tr>
</thead>
<tbody>
<tr v-for="(row, index) in tableData" :key="index">
<td v-for="cell in row" :key="cell">{{ cell }}</td>
</tr>
</tbody>
</table>
</div>
</div>
</template>
<script>
import { ref } from 'vue';
import * as XLSX from 'xlsx';
export default {
setup() {
const headers = ref([]);
const tableData = ref([]);
const changeExcel= (event) => {
const files = e.target.files
if (files.length <= 0) {
return false
} else if (!/\.(xls|xlsx)$/.test(files[0].name.toLowerCase())) {
console.log('上傳格式不正確,請上傳xls或者xlsx格式')
return false
}
const reader = new FileReader();
reader.onload = (e) => {
const data = e.target.result;
const workbook = XLSX.read(data, { type: 'binary' });
const sheetName = workbook.SheetNames[0];
const worksheet = workbook.Sheets[sheetName];
const json = XLSX.utils.sheet_to_json(worksheet, { header: 1 });
headers.value = json[0]; // 表頭
tableData.value = json.slice(1); // 表格數(shù)據(jù)
};
reader.readAsBinaryString(files);
};
return {
headers,
tableData,
handleFileUpload,
};
},
};
</script>
<style scoped>
table {
width: 100%;
border-collapse: collapse;
}
th, td {
border: 1px solid #ccc;
padding: 8px;
text-align: left;
}
</style>3. 使用組件
在主應(yīng)用文件(如 App.vue)中引入并使用該組件:
<template>
<div id="app">
<ExcelUpload />
</div>
</template>
<script>
import ExcelUpload from './components/ExcelUpload.vue';
export default {
name: 'App',
components: {
ExcelUpload,
},
};
</script>4. 功能說明
文件上傳:通過 <input type="file"> 元素選擇 Excel 文件。
文件讀?。菏褂?FileReader 讀取文件內(nèi)容為二進(jìn)制字符串 。
解析為 JSON:使用 xlsx 庫將 Excel 數(shù)據(jù)轉(zhuǎn)換為 JSON 格式 。
數(shù)據(jù)展示:將解析后的表頭和數(shù)據(jù)展示在表格中。
5. 擴(kuò)展功能
錯誤處理:在文件讀取和解析過程中添加錯誤處理,提示用戶文件格式錯誤或解析失敗。
大文件優(yōu)化:對于大文件,可以分頁顯示數(shù)據(jù)或使用異步加載。
自定義解析邏輯:根據(jù)實際需求,對數(shù)據(jù)進(jìn)行格式轉(zhuǎn)換或校驗。
通過以上步驟,你可以在 Vue 3 項目中實現(xiàn)本地上傳 Excel 文件并解析為 JSON 數(shù)據(jù)的功能。
以上就是vue3采用xlsx庫實現(xiàn)本地上傳excel文件功能的詳細(xì)內(nèi)容,更多關(guān)于vue3 xlsx實現(xiàn)excel上傳的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
Vue+ElementUI實現(xiàn)從后臺動態(tài)填充下拉框的示例代碼
本文主要介紹了Vue+ElementUI實現(xiàn)從后臺動態(tài)填充下拉框的示例代碼,文中通過示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下2022-02-02
vue.extend與vue.component的區(qū)別和聯(lián)系
這篇文章主要介紹了vue.extend與vue.component的區(qū)別和聯(lián)系,本文通過實例代碼給大家介紹的非常詳細(xì),具有一定的參考借鑒價值 ,需要的朋友可以參考下2018-09-09
elementUI+vue+printJs實現(xiàn)頁面表格數(shù)據(jù)打印功能實例
打印功能是一個很普遍的需求,這兩天我又遇到了,這篇文章主要介紹了elementUI+vue+printJs實現(xiàn)頁面表格數(shù)據(jù)打印功能的相關(guān)資料,包括安裝依賴、引用插件、設(shè)置打印區(qū)域div、綁定按鈕事件加載全量數(shù)據(jù)并調(diào)用printJS方法,需要的朋友可以參考下2025-06-06

