在详细介绍前,先展示下效果
第一步,下载xlsx插件
npm install xlsx@0.16.0
在需要的文件中import导入“import xlsx form 'xlsx'” 或 import { read, untils } from 'xlsx'
*第二步:编写导入按钮
*
<el-upload
class="upload-demo"
action=""
drag
ref="upload"
accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.ms-excel"
:limit="limitUpload"
:on-exceed="handleExceed"
:on-change="handleChange"
:auto-upload="false"
>
<i class="el-icon-upload"></i>
<div class="el-upload__text">将文件拖到此处,或<em>点击上传</em></div>
<div class="el-upload__tip"><span style="color:red;font-weight:800;">请上传 .xls / .xlsx 格式文件</span></div>
</el-upload>
handleChange(file) {
const _this = this
// _this.tableData = []
const fileName = file.name;
console.log(fileName);
const reader = new FileReader();
//提取excel中文件内容
reader.readAsArrayBuffer(file.raw);
reader.onload = function () {
const buffer = reader.result;
const bytes = new Uint8Array(buffer);
const length = bytes.byteLength;
let binary = "";
for (let i = 0; i < length; i++) {
binary += String.fromCharCode(bytes[i]);
}
const XLSX = require("xlsx"); //import xlsx from 'xlsx'
console.log(XLSX);
//转换二进制
const wb = XLSX.read(binary, {
type: "binary",
});
const outdata = XLSX.utils.sheet_to_json(wb.Sheets[wb.SheetNames[0]]);
console.log(outdata);
//这里for循环将excel表格数据转化成json数据
outdata.forEach((i) => {
let obj = {
Project: i.Project,
ERS1: i.ERS1,
CategoryRel: i.CategoryRel,
TestItem: i.TestItem,
TestConditionParameter: i.TestConditionParameter,
Equipment: i.Equipment,
Fixture: i.Fixture,
SampleOrientation: i.SampleOrientation,
RecoveryTime: i.RecoveryTime,
Qty: i.Qty,
SamplingFreq: i.SamplingFreq,
Duration: i.Duration,
ReadPoint: i.ReadPoint,
};
//连接后台接口添加到后台数据库
_this.$http({
method: 'post',
url: '/ERS/InsertERS',
data: obj
})
.then((response) => {
if (response.data["header"]["code"] == 0) {
// _self.resetForm(formName);
_this.getData();
// _this.$message.success('添加成功');
// this.$refs.form.resetFields()
// console.log( _self.txt)
} else {
_this.$message.error(response.data["header"]["message"]);
}
})
.catch((error) => {
_this.$message.error(error.toString());
});
// _this.tableData.push(obj); //此处是把数据添加到表格中
});
};
},
以下为添加的对应字段表格显示,以此类推