安装
npm install xlsx@0.16.0 --save
npm install file-saver --save
页面引入
import XLSX from ‘xlsx’;
const FileSaver = require(‘file-saver’)
代码部分`
html
<label for="explore" class="exploreCss">
<input type="file" id="explore" accept=".xls,.xlsx" style="display: none"
@change="readExcel($event)">导入Excel
</label>
js`
import XLSX from 'xlsx';
const FileSaver = require('file-saver')
// 导入表格
readExcel(e) {
// 读取表格文件
const that = this
const files = e.target.files
if (files.length <= 0) {
return false
} else if (!/\.(xls|xlsx)$/.test(files[0].name.toLowerCase())) {
this.$message({
message: '上传格式不正确,请上传xls或者xlsx格式',
type: 'warning'
})
return false
} else {
// 更新获取文件名
that.formName = files[0].name
}
const fileReader = new FileReader()
fileReader.onload = ev => {
try {
const data = ev.target.result
const workbook = XLSX.read(data, {
type: 'binary'
})
const wsname = workbook.SheetNames[0] // 取第一张表
const ws = XLSX.utils.sheet_to_json(workbook.Sheets[wsname]) // 生成json表格内容
that.userIdsLists = []
// 从解析出来的数据中提取相应的数据
//要和文档内字段对应
ws.forEach(item => {
that.userIdsLists.push({
cdk: item['卡券CDK'],
userId: item['用户ID'],
})
})
that.userCount = that.userIdsLists.length
//that.userIdsLists 表格数据
} catch (e) {
return console.log(e)
}
}
fileReader.readAsBinaryString(files[0])
},