首先引入依赖模块:
npm install xlsx --save
在 main.js 中引入
import XLSX from 'xlsx'
Vue.prototype.XLSX = XLSX;
打开对话框
<el-button type="primary" @click="showPlanDialogVisible = true">上传计划</el-button>
对话框
<!-- 上传计划对话框-->
<el-dialog
title="上传计划"
:visible.sync="showPlanDialogVisible"
width="21.3%"
center>
<el-upload
ref="upload"
drag
action
accept=".xls,.xlsx"
:on-exceed="exceed"
:limit="1"
:on-remove="remove"
:http-request="uploadFile">
<i class="el-icon-upload"></i>
<div class="el-upload__text">
将文件拖到此处,或
<em>点击上传</em>
</div>
<div class="el-upload__tip" slot="tip">1次只能上传1个xls文件,且不超过10M</div>
</el-upload>
<span slot="footer">
<el-button @click="cancel">取 消</el-button>
<el-button type="primary" @click="uploadPlan">确 定</el-button>
</span>
</el-dialog>
js部分
export default {
data() {
return {
showPlanDialogVisible: false,
fileList: [], // excel文件列表
}
},
methods: {
//解析excel
uploadFile(params) {
const _file = params.file;
const fileReader = new FileReader();
fileReader.onload = (ev) => {
try {
const data = ev.target.result;
const workbook = XLSX.read(data, { type: 'binary' });
for (let sheet in workbook.Sheets) {
//循环读取每个文件
const sheetArray = XLSX.utils.sheet_to_json(workbook.Sheets[sheet]);
//若当前sheet没有数据,则continue
if(sheetArray.length === 0){
continue;
}
console.log("读取文件", sheetArray);
this.fileList = sheetArray;
// for(let item in sheetArray){
// let rowTable = {};
// //这里的rowTable的属性名注意要与上面表格的prop一致
// //sheetArray的属性名与上传的表格的列名一致
// rowTable.name = sheetArray[item].station_name;
// // rowTable.age = sheetArray[item].;
// this.fileList.push(rowTable)
// }
}
} catch (e) {
this.$message.warning('文件类型不正确!');
}
};
fileReader.readAsBinaryString(_file);
},
//上传1个以上文件时弹窗提示错误
exceed: function() {
this.$message.error("最多只能上传1个xls文件");
},
//删除文件
remove() {
this.fileList = [];
},
// 取消上传
cancel() {
this.showPlanDialogVisible = false;
this.$refs.upload.clearFiles(); // 点击取消清空上传文件位置的列表文件
this.$message.info('已取消');
},
// 上传文件
uploadPlan() {
if (this.fileList.length === 0) return this.$message.error('请选择要上传的文件!')
console.log(this.fileList)
this.$axios({
method: 'post',
url:'/api/get_station_profiles',
data:JSON.stringify(this.fileList),
}).then(res => {
console.log('上传文件:', res);
if (res.data.code !== 200) return this.$message.error('上传失败!');
this.showPlanDialogVisible = false;
this.$refs.upload.clearFiles();
this.planData()
});
},
}
}