Vue配合element-ui实现excel导入导出
文章参考:vue后台项目模板,添加链接描述
项目运行:
npm install xlsx file-saver -S
npm install script-loader -S -D
终点在src目录下建一个名字为 vendor 的文件夹,里面放两个文件,文件 名不要改,会发生不可预知错误
文件下载地址:
添加链接描述
//导出为excfel
exportEx(){
import('@/vendor/Export2Excel').then(excel => {
//excel-list 非必填项
const filterVal = ['numb','type', 'name', 'numer','price', 'date', 'recivedate','category','mode','address','people','descs']
//表头必填项
const tHeader = ['numb','type', 'name', 'numer','price', 'date', 'recivedate','category','mode','address','people','descs']
//this.templist为获取到的选中的数组
const list = this.templist
const data = this.formatJson(filterVal, list)
excel.export_json_to_excel({
header: tHeader,
data,
filename: this.filename,
autoWidth: this.autoWidth,
bookType: this.bookType
})
})
},
formatJson(filterVal, jsonData) {
return jsonData.map(v => filterVal.map(j => {
if (j === 'timestamp') {
return parseTime(v[j])
} else {
return v[j]
}
}))
},
excel导入,vue文件在上面仓库
import UploadExcelComponent from "@/components/UploadExcel/index"
<upload-excel-component :on-success="handleSuccess" :before-upload="beforeUpload"></upload-excel-component>
</el-col>
// 导入前的判断,可对导入文件做处理
beforeUpload(file) {
const isLt1M = file.size / 1024 / 1024 < 1
if (isLt1M) {
return true
}
this.$message({
message: 'Please do not upload files larger than 1m in size.',
type: 'warning'
})
return false
},
// 旧数据导入成功的回调
handleSuccess({ results, header }) {
console.log('返回值',results)
//把数据进行排序
let val = results.sort(this.compare('a'))
console.log(val)
localStorage.setItem('oldvale', JSON.stringify(val))
this.getList()
},