首先下载依赖
0.16.0 版本 的 xlsx
npm install xlsx@0.16.0 --save
import XLSX from 'xlsx';
一、 上传文件后获取数据,引用element-ui中的upload
<el-upload
class="upload-demo"
action="/"
:on-change="getExcel"
:auto-upload="false"
:show-file-list="false"
>
<el-button size="small" type="primary">上传文件</el-button>
</el-upload>
二、 上传文件后获取数据,input 中 type= file 上传
<input type=”file“ @change="getExcel"/>
js代码
getExcel(file) {
const types = file.name.split(".")[1];
const fileType = ["xlsx", "xlc", "xlm", "xls", "xlt", "xlw", "csv"].some(
item => item === types
);
if (!fileType) {
this.$message("格式错误!请重新选择");
return;
}
this.analysis(file).then(tabJson => {
if (tabJson && tabJson.length > 0) {
this.xlsxJson = tabJson;
console.log(JSON.stringify(this.xlsxJson[0].sheet))
console.log("数据", this.xlsxJson);
}
});
},
analysis(file) {
return new Promise(function(resolve, reject) {
const reader = new FileReader();
reader.onload = function(e) {
const data = e.target.result;
this.wb = XLSX.read(data, {
type: "binary"
});
const result = [];
this.wb.SheetNames.forEach(sheetName => {
console.log(sheetName)
result.push({
sheetName: sheetName,
sheet: XLSX.utils.sheet_to_json(this.wb.Sheets[sheetName])
});
});
resolve(result);
};
reader.readAsBinaryString(file.raw);
});
},