功能
数据上传处理一般都是后端去做的,但最近开发中遇到了前端处理数据的情况,无法让后端处理Excel表格,因此前端对Excel数据进行处理
实现
基于element、XLSX.js
代码
<el-upload
action="#"
:http-request="handleHttpRequest">
<el-button id="uploadButton" size="small" type="primary">上传</el-button>
</el-upload>
handleHttpRequest(file:{}) {
if (!!file) {
const reader = new FileReader()
const upload_sheet_file = _.get(file, 'file')
if (upload_sheet_file) {
reader.onload = (e: any) => {
try {
onst data = e.target.result
const workbook = XLSX.read(data, {
raw: true,
cellNF: true,
cellText: true,
type: 'binary',
cellDates: true,
cellFormula: true
})
if (workbook) {
const analyze_row_list = XLSX.utils.sheet_to_json(workbook.Sheets[workbook.SheetNames[0]])
analyze_row_list.forEach(item => {
let row = {}
for(let key in item) {
this.dataHeadList.forEach(head => {
if (key == head.name) {
this.$set(row, head.binding, item[key])
}
})
}
this.showTableData.push(row)
})
}
} catch(e) {
this.$message('解析失败')
} finally {
console.log('解析操作完成')
}
}
}
reader.readAsBinaryString(upload_sheet_file)
}
}