Vue表格导出、导出、打印实现
1.代码下载
1.1下载两个相关的js代码:
1.2.Tab.vue:
<template>
<div>
<!-- v-print为Vue打印插件,需要安装相关包,运行npm install 即可 -->
<el-button v-print="printObj" style="float: left; margin-right: 50px;">打印</el-button>
<!-- el-upload为Element中的"Upload 上传"插件,相关的参数,如on-change,file-list等,建议配合Element官网食用 -->
<el-upload style="float: left;" class="upload-demo" action=""
accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.ms-excel"
:on-change="handleExcelFileChange" :on-exceed="handleExcelFileExceed" :on-remove="handleExcelFileRemove"
:file-list="excelFileList" :limit="1" :auto-upload="false">
<el-button size="small" type="warning" plain>选择文件</el-button>
<div slot="tip" class="el-upload__tip" style="float: right; margin-right: 20px;">只能上传 xlsx/xls 类型的文件</div>
</el-upload>
<!-- 触发导入数据函数,显示弹出框,搜集文件 -->
<el-button style="float: left; margin-right: 50px;" type="success" @click="handleImport()" round>导入数据
</el-button>
<!-- 触发导入函数,将数据渲染到表格中 -->
<el-button type="primary" size="small" @click="downloadExcel" style="float: left; margin-right: 50px;">导出
</el-button>
<!-- 表格展示页面 -->
<el-table id="mytable" :data="tableData" style="width: 100%">
<el-table-column prop="date" label="日期" width="180">
</el-table-column>
<el-table-column prop="name" label="姓名" width="180">
</el-table-column>
<el-table-column prop="address" label="地址">
</el-table-column>
<el-table-column label="操作">
<template slot-scope="scope">
<el-button size="mini" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
<el-button size="mini" type="danger" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
</template>
</el-table-column>
</el-table>
</div>
</template>
<script>
export default {
data() {
return {
tableData: [{ //用来进行数据渲染
date: '2016.05.02',
name: '王小虎',
address: '上海市普陀区金沙江路 1518 弄'
}, {
date: '2016.05.04',
name: '王小虎',
address: '上海市普陀区金沙江路 1517 弄'
}, {
date: '2016.05.01',
name: '王小虎',
address: '上海市普陀区金沙江路 1519 弄'
}, {
date: '2016.05.03',
name: '王小虎',
address: '上海市普陀区金沙江路 1516 弄'
}],
printObj: {
id: "mytable", //Vue-print打印插件相关参数配置
popTitle: '打印的标题',
},
excelFileList: [], //获取文件数据,将其转换为列表形式
excelFile: null, //文件数据
len: 4 //当前表格数据个数
}
},
methods: {
handleExcelFileChange(file, fileList) {
this.excelFile = file.raw //获取文件
},
handleExcelFileRemove(file, fileList) {
this.excelFile = null //当文件被移除的时候,将文件数据制空
},
handleExcelFileExceed(file, fileList) {
//当获取的文件数量大于limit属性值规定的数,进行错误提示
this.tip("error", "一次只能导入一个文件的数据!")
},
//将数据转换为列表形式函数
parseExcel(obj) {
let promise = new Promise(function(resolve, reject) {
var rABS = false; // 是否将文件读取为二进制字符串
var f = obj;
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]);
}
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]]);
this.da = [...outdata]
let arr = []
this.da.map(v => {
let obj = {}
obj.date = v['日期'] //注意这里的obj属性,data,name,address和表格列表中的属性一样,这样渲染时才不会出错,
obj.name = v['姓名'] //这里一定要注意,非常重要,data,name,address为你表格各列属性
obj.address = v['地址'] //v[]数组中的字符串为上传的数据的属性名称
arr.push(obj) //建议这里打印一下数据,便于理解。
console.log("这是读取到的表格数据",v);
})
console.log("这是将数据传入列表中的表示",arr)
resolve(arr)
}
reader.readAsArrayBuffer(f);
}
if (rABS) {
reader.readAsArrayBuffer(f);
} else {
reader.readAsBinaryString(f);
}
})
console.log("这是最后返回的数据",promise)
return promise
},
//数据导入函数
handleImport() {
var that = this
if (this.excelFile) {
if ((this.excelFile.type ==
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet') ||
(this.fileTemp.type == 'application/vnd.ms-excel')) {
this.parseExcel(this.excelFile).then((res) => {
console.log("读取到的数据", res[0]) // 获取解析到的数据
for (var i = 0; i < res.length; i++) {
this.tableData.push(res[i]); //这里直接将数据push到表格列表中,所以之前要求属性名称要对应
}
})
} else {
this.tip("warning", "附件格式错误,请重新选择!")
}
} else {
this.tip("warning", "请选择要导入的附件!")
}
},
tip(type, message) {
if (type !== "info") {
this.$message({
message: message,
showClose: true,
type: type
})
} else {
this.$message({
message: message,
showClose: true
})
}
},
//这两个是最后一列的操作函数,是elmentUI自带的
handleEdit(index, row) {
console.log(index, row);
},
handleDelete(index, row) {
console.log(index, row);
},
//以下是导出相关的三个函数
// 格式转换,直接复制即可
formatJson(filterVal, jsonData) {
return jsonData.map(v => filterVal.map(j => v[j]))
},
// 数据写入excel
export2Excel() {
var that = this
require.ensure([], () => {
const {
export_json_to_excel
} = require('@/excel/export2Excel') // 这里必须使用绝对路径,使用@/+存放export2Excel的路径
const tHeader = ['日期', '姓名', '地址'] // 导出的excel的表格各列的属性
const filterVal = ['date', 'name', 'address'] // 对象属性,对应于tableData的属性
const list = that.excelData //json数组对象,接口返回的数据
const data = that.formatJson(filterVal, list)
export_json_to_excel(tHeader, data, '数据') // 导出的Excel表格名称
})
},
//文件导出函数
downloadExcel() {
this.$confirm('将导出为excel文件,确认导出?', '提示', {
confirmButtonText: '确定',
cancelButtonText: '取消',
type: 'warning'
}).then(() => {
this.excelData = this.tableData //想要导出所有数据,则这里调用后台数据接口
this.export2Excel()
}).catch(() => {
})
},
}
}
</script>
<style>
</style>
1.3.main.js文件:
import Vue from 'vue';
import ElementUI from 'element-ui';
import 'element-ui/lib/theme-chalk/index.css';
import App from './App.vue';
Vue.use(ElementUI);
import Print from 'vue-print-nb' //文件打印助手
Vue.use(Print)
Vue.config.productionTip = false //关闭vue的生产提示,否则console上报红
new Vue({
render: h => h(App),
}).$mount('#app')
1.4.App.vue
<template>
<div >
<Tab></Tab>
</div>
</template>
<script>
import Tab from './components/Tab.vue'
export default {
name: 'app',
components: {
Tab
}
}
</script>
<style>
</style>
2.代码调试
- 构建组件,在App.vue中声明,调用:
- 导入功能,代码修改,这里的属性名和数组中字符名需要对应到自己的表格和Exccel数据。
-
导出功能,代码修改,tHeader中的是想导出后的表格中的各列属性名,filterVal为tableData中的属性,需要修改自己的。
-
整体代码结构:
-
将文件都下载好了,可以整个项目运行
npm install
,进行整个依赖下载,同时整个项目是在ElementUI的环境下使用的,需要配置以下ElementUI环境,同时需要下载相关的其他文件依赖。 -
依次执行以下命令:
npm i element-ui -S
npm install -S file-saver
npm install -S xlsx
npm install -D script-loader
- 这里也有整个代码下载,可以直接跑起来:点击下载
3.效果展示
3.1打印实现:
3.2导入实现:
3.3导出实现:
4.总结
建议先跑起来这个代码,
将代码看一遍
,之后再将这些功能整合到自己已有的项目中。
一定要好好看一遍Tab.vue这个代码哈,这样再整合的时候就不会出错了。