方式一、用现成的 Upload 标签
<template>
<div>
<Card title="导入EXCEL">
<Row>
<div style="float:left">
<Upload action="" :before-upload="handleBeforeUpload" accept=".xls, .xlsx">
<Button icon="ios-cloud-upload-outline" :loading="uploadLoading" @click="handleUploadFile">上传文件</Button>
</Upload>
</div>
<div style="float:left">
<Button type="primary" @click="submitData" style="margin-left:40px">提交数据</Button>
</div>
</Row>
<Row>
<div class="ivu-upload-list-file" v-if="file !== null">
<Icon type="ios-stats"></Icon>
{{ file.name }}
<Icon v-show="showRemoveFile" type="ios-close" class="ivu-upload-list-remove" @click.native="handleRemove()"></Icon>
</div>
</Row>
<Row>
<transition name="fade">
<Progress v-if="showProgress" :percent="progressPercent" :stroke-width="2">
<div v-if="progressPercent == 100">
<Icon type="ios-checkmark-circle"></Icon>
<span>成功</span>
</div>
</Progress>
</transition>
</Row>
</Card>
<Row class="margin-top-10">
<Table :columns="tableColumns" :data="tableData" :loading="tableLoading"></Table>
</Row>
</div>
</template>
<script>
import { logintest } from '@/api/data'
import { getUserList } from '@/api/user'
import { getTbm, addTbm, getTbcolumn} from '@/api/data'
import excel from '@/libs/excel'
import qs from 'qs'
export default {
name: 'af02',
data () {
return {
tb: 'tbmaf01',
tableTitle: [],
tableData:[],
tdLen:'',
tbColumn: {
tb: 'tbmaf01'
},
tableColumns: [
],
uploadLoading: false,
progressPercent: 0,
showProgress: false,
showRemoveFile: false,
file: null,
tableLoading: false
}
},
methods: {
//数据提交后台
submitData() {
let _this = this
var data = JSON.stringify(this.tableData)
if(this.tableData.length == 0){
this.$Notice.warning({
title: '上传数据错误',
desc: '没有数据可上传。'
})
return
}
addTbm(data).then(res => {
let i = res.data.data
this.$Message.success('成功汇入' + i + '笔数据')
})
},
initUpload () {
this.file = null
this.showProgress = false
this.loadingProgress = 0
this.tableData = []
},
handleUploadFile () {
this.initUpload()
},
handleRemove () {
this.initUpload()
this.$Message.info('上传的文件已删除!')
},
handleBeforeUpload (file) {
const fileExt = file.name.split('.').pop().toLocaleLowerCase()
if (fileExt === 'xlsx' || fileExt === 'xls') {
this.readFile(file)
this.file = file
} else {
this.$Notice.warning({
title: '文件类型错误',
desc: '文件:' + file.name + '不是EXCEL文件,请选择后缀为.xlsx或者.xls的EXCEL文件。'
})
}
return false
},
// 读取文件
readFile (file) {
let _this = this
const reader = new FileReader()
reader.readAsArrayBuffer(file)
reader.onloadstart = e => {
this.uploadLoading = true
this.tableLoading = true
this.showProgress = true
}
reader.onprogress = e => {
this.progressPercent = Math.round(e.loaded / e.total * 100)
}
reader.onerror = e => {
this.$Message.error('文件读取出错')
}
reader.onload = e => {
this.$Message.info('文件读取成功')
const data = e.target.result
const { header, results } = excel.read(data, 'array')
//const tableTitle = header.map(item => { return { title: item, key: item } })
// 以下为处理数据
let arr = [];
results.map( v => {
let obj = {}
_this.tableTitle.forEach((t) => {
//obj[t['key']] = v[t['title']]
// 例如
obj.name = t['姓名'] //对象属性对应导入的excel列名
obj.age = t['年龄']
})
arr.push(obj)
})
_this.tableData=arr
this.uploadLoading = false
this.tableLoading = false
this.showRemoveFile = true
}
}
},
mounted () {
// 初始化表头
getTbcolumn(qs.stringify(this.tbColumn)).then(res => {
this.tableColumns = res.data.data
this.tableTitle = this.tableColumns.map(item => { return { title: item.title, key: item.key } })
})
}
}
</script>
方式二、使用xlsx
1、安装插件
npm install -S file-saver xlsx
npm install -D script-loader
npm install xlsx
2、引入 import XLSX from 'xlsx'
3、页面
<template>
<Card>
<input type="file" ref="myfile" />
<Button @click="importData" type="success" icon="el-icon-upload2">汇入数据</Button>
<Button type="info" @click="reset()" style="margin-left:20px">重置</Button>
<Button type="primary" @click="submitData()" style="margin-left:20px">提交数据</Button>
<Table stripe border :columns="tableColumns"
:data="tableData" style="margin-top:20px;"></Table>
</Card>
</template>
4、 js
data () {
return {
tableData:[],
tdLen:'',
tableColumns: [
]
}
},
methods: {
//数据提交后台
submitData() {
let _this = this
var data = JSON.stringify(this.tableData)
addTbm(data).then(res => {
let i = res.data.data
alert('成功汇入'+i)
})
},
//数据导入页面
importData(){
let _this = this
let myfile = this.$refs.myfile;
let files = myfile.files;
this.file = files[0];
var rABS = false; //是否将文件读取为二进制字符串
var f = this.file;
var reader = new FileReader();
FileReader.prototype.readAsBinaryString = function(f) {
var binary = "";
var rABS = false; //是否将文件读取为二进制字符串
var pt = this;
var wb; //读取完成的数据
var outdata;
var reader = new FileReader();
reader.onload = function(e) {
var bytes = new Uint8Array(reader.result);
var length = bytes.byteLength;
for (var i = 0; i < length; i++) {
binary += String.fromCharCode(bytes[i]);
}
//此处引入,用于解析excel
var XLSX = require("xlsx");
if (rABS) {
wb = XLSX.read(btoa(fixdata(binary)), {
//手动转化
type: "base64"
});
} else {
wb = XLSX.read(binary, {
type: "binary"
});
}
outdata = XLSX.utils.sheet_to_json(wb.Sheets[wb.SheetNames[0]]);
//outdata就是读取的数据(不包含标题行即表头,表头会作为对象的下标)
//此处可对数据进行处理
let arr = [];
let cDate = _this.getCurrDate()
outdata.map(v => {
let obj = {}
obj.a1 = v['资产名称']
obj.a2 = v['资产编号']
arr.push(obj)
});
_this.tableData=arr;
_this.tdLen=arr.length;
return arr;
};
reader.readAsArrayBuffer(f);
};
if (rABS) {
reader.readAsArrayBuffer(f);
} else {
reader.readAsBinaryString(f);
}
},
reset(){
this.$refs.myfile.value = ''
this.tableData = []
}
}