本项目需要上传一个excel表格,并把表格里面的数据给拿出来,传递给后端。
一: 首先 安装一下xlsx插件 npm install xlsx --save
下面来看一下具体操作:
思路:先创建一个方法,以便于在多个地方调用。
/**
* 导出 excel 文件
* @param array JSON 数组
* @param sheetName 第一张表名
* @param fileName 文件名
*/
const exportExcelFile = (array, sheetName = '表1', fileName = '补考考试安排.xlsx') => {
const jsonWorkSheet = XLSX.utils.json_to_sheet(array);
const workBook = {
SheetNames: [sheetName],
Sheets: {
[sheetName]: jsonWorkSheet,
}
};
return XLSX.writeFile(workBook, fileName);
}
/**
* 导入 excel 文件
* @param file 文件内容
*/
const uploadExcelFile = (file) => {
if (!file) {
return false
} else if (!/\.(xls|xlsx)$/.test(file.name.toLowerCase())) {
this.$message.error('上传格式不正确,请上传xls或者xlsx格式')
}
//FileReader,对象专门操作二进制数据,主要将文件内容读到内存
const reader = new FileReader();
//.readAsArrayBuffer,读取指定的lob 或 File内容
reader.readAsBinaryString(fileObj)
reader.onload = (event) => {
const arrayBuffer = event.target.result;
const options = { type: 'binary' };
//从表格字节提取数据
const workbook = XLSX.read(arrayBuffer, options);
//读取第一张表的数据
const wsname = workbook.SheetNames[0];
console.log('wsname', wsname);
//生成js表格内容
const sheetJson = XLSX.utils.sheet_to_json(workbook.Sheets[wsname])
return sheetJson
}
}
然后,就可以在页面中使用导入导出方法,下面看一下具体的用法:
// 导入
//这里使用了element-ui 的 el-Upload组件
handleChange(file, fileList) {
let fileObj = file.raw,
let sheetJson = uploadExcelFile(fileObj),
//将数据改成要使用的样式
// .....
},
//导出
exportExcel(data) {
let sheetJson = JSON.parse(JSON.stringify(data))
//数据转换成合适的格式
//...
exportExcelFile(sheetJson)
}
>页面结构
<el-upload class="upload-demo" drag action="" :on-change="handleChange"
accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.ms-excel">
<i class="el-icon-upload"></i>
<div class="el-upload__text">将文件拖到此处,或<em>点击上传</em></div>
<div class="el-upload__tip" slot="tip">只能上传excal文件,且不超过500kb</div>
</el-upload>
<!-- 表单-->
<el-table :data="tableData" border style="width: 100%" max-height="530">
<el-table-column type="index">
</el-table-column>
<el-table-column prop="stuId" label="学号">
</el-table-column>
<el-table-column prop="stuName" label="姓名">
</el-table-column>
<el-table-column prop="courseName" label="课程名称">
</el-table-column>
<el-table-column prop="courseDept" label="开课学院">
</el-table-column>
<el-table-column prop="stuDept" label="学生所在学院">
</el-table-column>
<el-table-column prop="teacherName" label="任课教师">
</el-table-column>
</el-table-column>
</el-table>
<div class="footer-button-left">
<el-button type="primary" @click="exportExcel(tableData2)">导出</el-button>
<el-button type="primary" @click="uploadExcel">导入</el-button>
</div>
遇到的坑
1.下载xlsx时报错,方法:降低xlsx的版本