vue Excel 表格批量新增
时间: 2023-10-14 22:30:56 浏览: 48
你可以使用以下步骤实现 Vue Excel 表格批量新增:
1. 首先,你需要安装并导入 `xlsx` 模块,它可以让你读取和写入 Excel 文件。你可以使用如下代码安装它:
```
npm install xlsx
```
2. 在 Vue 组件中,你需要定义一个包含表格数据的数组。例如:
```
data() {
return {
tableData: [
{ id: 1, name: 'John', age: 30 },
{ id: 2, name: 'Alice', age: 25 }
]
}
}
```
3. 在模板中,你需要添加一个文件上传组件和一个按钮,用于触发上传事件。例如:
```
<template>
<div>
<input type="file" ref="fileInput" @change="uploadFile">
<button @click="addRows">批量新增</button>
<table>
<thead>
<tr>
<th>ID</th>
<th>姓名</th>
<th>年龄</th>
</tr>
</thead>
<tbody>
<tr v-for="item in tableData" :key="item.id">
<td>{{ item.id }}</td>
<td>{{ item.name }}</td>
<td>{{ item.age }}</td>
</tr>
</tbody>
</table>
</div>
</template>
```
4. 在组件的方法中,你需要添加两个函数:`uploadFile` 和 `addRows`。`uploadFile` 函数用于读取上传的 Excel 文件,`addRows` 函数用于将文件中的数据添加到表格数据数组中。例如:
```
methods: {
uploadFile() {
const file = this.$refs.fileInput.files[0]
const reader = new FileReader()
reader.onload = (e) => {
const data = new Uint8Array(e.target.result)
const workbook = XLSX.read(data, { type: 'array' })
const sheetName = workbook.SheetNames[0]
const worksheet = workbook.Sheets[sheetName]
const json = XLSX.utils.sheet_to_json(worksheet)
this.tableData = json
}
reader.readAsArrayBuffer(file)
},
addRows() {
// 这里可以处理数据并添加到 tableData 数组中
}
}
```
在 `uploadFile` 函数中,我们首先获取上传的文件,然后使用 `FileReader` 对象读取文件内容。一旦读取完成,我们使用 `xlsx` 模块将数据转换成 JSON 格式。最后,我们将 JSON 数据添加到 `tableData` 数组中,从而更新表格。
在 `addRows` 函数中,你可以处理表格数据并将处理后的数据添加到 `tableData` 数组中。例如,你可以使用 `Array.push()` 方法将新行添加到数组中。
这样,你就可以实现 Vue Excel 表格批量新增了。