项目需要上传Excel并需要前端解析,将解析的数据放进表格中,方便教师检查是否有误。如有误可直接在前端进行修改,修改之后传到后端进行计算。
这里采用了avue,FileSaver,xlsx对Excel进行解析并渲染。

结构代码
<div style="width:400px">
<el-button type="primary" @click="handleExcel">下载 excel</el-button>
<el-button type="success" @click="handleExcel1">下载 多级表头excel</el-button>
</div>
使用前需要安装好相关依赖
<script src="https://cdn.staticfile.org/FileSaver.js/2014-11-29/FileSaver.min.js"></script>
<script src="https://cdn.staticfile.org/xlsx/0.18.2/xlsx.full.min.js"></script>
我这个项目里的Excel表格的表头是动态的,根据后端传回来的进行渲染构造。
js部分代码
async getOption() {
const { data: res } = await this.$http.post(
"getCourseTargetPoint",
this.$route.params
);
if (res.meta.status != "200") return this.$message.error("获取失败!");
this.$message.success("获取成功!");
this.option = res.data;
console.log("测试xlx")
console.log(this.option)
this.pointArray = res.data.points;
this.getUserId();
},
目前已经获取到数据,接下来我们处理上传excel事件
handleChange(file, fileLis) {
this.$Export.xlsx(file.raw).then((data) => {
this.list = data.results;
console.log("测试传输进来的")
console.log(this.list);
});
},
这是我们进行测试的Excel

现在上传

这是上传后的数据,为了方便后端计算,因为这里表头不是固定的,可能一门课有多个指标点,所以需要前端包装好。这里做一个大模拟进行包装。
async handleUpload() {
for (var item of this.list) {
for (var arr of this.pointArray) {
const str1 = "指标点Id(" + arr.tpId + ")";
const str2 = "指标点(" + arr.tpNo + ")教师评成绩";
const str3 = "指标点(" + arr.tpNo + ")学生评成绩";
//每一行的指标点对象
const newObject = {
pointId: "",
teacherEstimate: "",
studentEstimate: "",
};
newObject.pointId = item[str1];
newObject.teacherEstimate = item[str2];
newObject.studentEstimate = item[str3];
this.rowArray.push(newObject);
}
//this.needObject.needArray.push(this.rowArray);
//this.needObject.needArray.push(this.rowArray);
//this.rowArray = []
}
this.needObject.needArray = this.rowArray
console.log(this.needObject.needArray)
this.needObject.userId = this.userId;
this.needObject.classId = this.classId;
this.needObject.courseNo = this.courseNo;
const { data: res } = await this.$http.post("recordCourseScore", this.needObject);
//if (res.meta.status != "200") return this.$message.error("上传失败!");
this.$message.success(res.meta.msg);
window.location.reload();
this.getUserId()
},
本文介绍如何使用avue、FileSaver及xlsx库在前端实现Excel文件的解析与数据展示,并通过前端处理后上传至后端进行进一步计算。
19万+

被折叠的 条评论
为什么被折叠?



