vue 实现excel表格
Vue 实现 Excel 表格功能
在 Vue 中实现 Excel 表格功能可以通过多种方式完成,包括使用第三方库或手动实现基础功能。以下是几种常见方法:
使用 xlsx 库处理 Excel 数据
安装 xlsx 库:
npm install xlsx
读取 Excel 文件并显示数据:
import * as XLSX from 'xlsx';
export default {
methods: {
handleFileUpload(event) {
const file = event.target.files[0];
const reader = new FileReader();
reader.onload = (e) => {
const data = new Uint8Array(e.target.result);
const workbook = XLSX.read(data, { type: 'array' });
const firstSheet = workbook.Sheets[workbook.SheetNames[0]];
this.tableData = XLSX.utils.sheet_to_json(firstSheet);
};
reader.readAsArrayBuffer(file);
}
},
data() {
return {
tableData: []
};
}
}
使用 vue-json-excel 导出数据
安装 vue-json-excel:
npm install vue-json-excel
在组件中使用:

import JsonExcel from 'vue-json-excel';
export default {
components: {
JsonExcel
},
data() {
return {
jsonData: [
{ name: 'John', age: 25 },
{ name: 'Jane', age: 30 }
],
fields: {
'Name': 'name',
'Age': 'age'
},
filename: 'user-data'
};
}
}
模板中使用:
<json-excel
:data="jsonData"
:fields="fields"
:name="filename + '.xls'">
Export to Excel
</json-excel>
使用 vue-element-admin 的 Excel 功能
如果项目基于 vue-element-admin,可以直接使用其内置的 Excel 功能:
import { export_json_to_excel } from '@/vendor/Export2Excel';
export default {
methods: {
exportExcel() {
const tHeader = ['姓名', '年龄'];
const filterVal = ['name', 'age'];
const data = this.tableData.map(v => filterVal.map(j => v[j]));
export_json_to_excel({
header: tHeader,
data,
filename: '用户数据'
});
}
}
}
纯前端实现简单表格编辑
对于不需要完整 Excel 功能的基本表格:

<template>
<div>
<table>
<thead>
<tr>
<th v-for="(header, index) in headers" :key="index">{{ header }}</th>
</tr>
</thead>
<tbody>
<tr v-for="(row, rowIndex) in tableData" :key="rowIndex">
<td v-for="(cell, cellIndex) in row" :key="cellIndex" contenteditable @blur="updateCell(rowIndex, cellIndex, $event)">
{{ cell }}
</td>
</tr>
</tbody>
</table>
</div>
</template>
<script>
export default {
data() {
return {
headers: ['姓名', '年龄', '职位'],
tableData: [
['张三', '28', '工程师'],
['李四', '32', '经理']
]
};
},
methods: {
updateCell(rowIndex, cellIndex, event) {
this.$set(this.tableData[rowIndex], cellIndex, event.target.innerText);
}
}
};
</script>
使用 Handsontable 实现高级表格
安装 Handsontable:
npm install handsontable @handsontable/vue
在组件中使用:
import { HotTable } from '@handsontable/vue';
import Handsontable from 'handsontable';
export default {
components: {
HotTable
},
data() {
return {
hotSettings: {
data: [
['', 'Tesla', 'Mercedes', 'Toyota'],
['2020', 10, 11, 12],
['2021', 20, 11, 14]
],
colHeaders: true,
rowHeaders: true,
contextMenu: true,
licenseKey: 'non-commercial-and-evaluation'
}
};
}
}
模板中使用:
<hot-table :settings="hotSettings"></hot-table>
以上方法涵盖了从简单到复杂的 Excel 表格实现方案,可根据项目需求选择合适的方式。对于复杂需求,推荐使用专业库如 Handsontable 或 xlsx;对于简单需求,纯前端实现或轻量级库即可满足。






