给我写一段vue2的excel导入代码
时间: 2023-10-20 22:13:19 浏览: 131
好的,以下是一个简单的Vue 2 Excel导入示例,使用xlsx库实现:
```html
<template>
<div>
<input type="file" @change="handleFileUpload" />
<table>
<thead>
<tr>
<th v-for="(header, index) in headers" :key="index">{{ header }}</th>
</tr>
</thead>
<tbody>
<tr v-for="(row, index) in rows" :key="index">
<td v-for="(cell, index) in row" :key="index">{{ cell }}</td>
</tr>
</tbody>
</table>
</div>
</template>
<script>
import XLSX from 'xlsx';
export default {
data() {
return {
headers: [],
rows: [],
};
},
methods: {
handleFileUpload(event) {
const file = event.target.files[0];
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 headers = [];
const rows = [];
for (const cell in worksheet) {
const cellAddress = XLSX.utils.decode_cell(cell);
const rowIndex = cellAddress.r;
const columnIndex = cellAddress.c;
const cellValue = worksheet[cell].v;
if (rowIndex === 0) {
headers[columnIndex] = cellValue;
} else {
rows[rowIndex - 1] = rows[rowIndex - 1] || [];
rows[rowIndex - 1][columnIndex] = cellValue;
}
}
this.headers = headers;
this.rows = rows;
};
reader.readAsBinaryString(file);
},
},
};
</script>
```
这段代码包括一个包含一个文件输入框和一个表格的Vue组件。当用户选择Excel文件并上传后,该组件会读取Excel文件的内容并将其显示在表格中。
阅读全文