vue实现excel上传预览
使用 vue-element-admin 的 Upload 组件实现上传
安装依赖 xlsx 用于解析 Excel 文件:
npm install xlsx --save
在 Vue 组件中引入依赖:
import XLSX from 'xlsx'
模板部分添加上传组件:
<el-upload
class="upload-demo"
action=""
:auto-upload="false"
:on-change="handleChange"
:show-file-list="false">
<el-button type="primary">点击上传</el-button>
</el-upload>
<el-table :data="tableData" style="width: 100%">
<!-- 表格列定义 -->
</el-table>
实现文件解析逻辑
在 methods 中添加处理函数:
handleChange(file) {
const reader = new FileReader()
reader.onload = e => {
const data = new Uint8Array(e.target.result)
const workbook = XLSX.read(data, { type: 'array' })
const firstSheetName = workbook.SheetNames[0]
const worksheet = workbook.Sheets[firstSheetName]
this.tableData = XLSX.utils.sheet_to_json(worksheet)
}
reader.readAsArrayBuffer(file.raw)
}
添加数据预览表格
在 data 中定义 tableData:
data() {
return {
tableData: []
}
}
表格列定义示例:
<el-table-column prop="name" label="姓名"></el-table-column>
<el-table-column prop="age" label="年龄"></el-table-column>
处理大数据量优化
对于大型 Excel 文件,建议添加分页或虚拟滚动:
{
data() {
return {
pageSize: 50,
currentPage: 1
}
},
computed: {
paginatedData() {
return this.tableData.slice(
(this.currentPage - 1) * this.pageSize,
this.currentPage * this.pageSize
)
}
}
}
添加文件类型验证
在上传组件中添加 accept 属性限制文件类型:
<el-upload
accept=".xlsx, .xls, .csv"
<!-- 其他属性 -->
>
</el-upload>
在 handleChange 方法中添加验证:
if (!file.name.endsWith('.xlsx') && !file.name.endsWith('.xls')) {
this.$message.error('请上传Excel文件')
return false
}
错误处理增强
添加解析错误处理:
reader.onerror = () => {
this.$message.error('文件读取失败')
}






