在诸如ERP管理系统,有些需求需要使用Excel的数据。
首先,在项目中安装 xlsx
模块
npm install xlsx --save
使用input的file属性,并定义事件
<template>
<div>
<!-- 如需让导入的文件名隐藏
<div style="height: 0;overflow: hidden;">
<input type="file" @change="handleChange($event.target.files[0])" id="selectedFile">
</div>
<input type="button" value="Browse..." onclick="document.getElementById('selectedFile').click();" /> -->
<input type="file" @change="handleChange($event.target.files[0])" id="selectedFile">
</div>
</template>
项目中正确引用xlsx模块
import * as XLSX from 'xlsx';
事件函数部分:
handleChange(file) {
const reader = new FileReader();
reader.onload = () => {
const workbook = XLSX.read(reader.result, { type: 'binary' });
console.log(workbook);
const sheet = workbook.Sheets[workbook.SheetNames[0]]
const data = XLSX.utils.sheet_to_json(sheet, { header: 1 })
console.log(data); //此处已经拿到处理过后的数据data,任由开发者使用
// 例如把提取的数据以对象的形式导入到数组中,供table使用
this.tableData = data.slice(1).map((item) => {
return { id: item[0], name: item[1], }
})
};
if (file instanceof File) {
reader.readAsBinaryString(file);
} else if (file instanceof Blob) {
reader.readAsBinaryString(new File([file], file.name));
}
},