首先,需要在一个没任何错误,可以成功启动的vue项目中
表格的导出
1.安装xlsx库
npminstallxlsx--save
2.file-saver
npminstallfile-saver--save
3.编写函数---新建exportsExcel.js文件
//将包导入importFileSaverfrom"file-saver";importXLSXfrom"xlsx";exportfunctiongetExcel(dom,title){varexcelTitle=title;varwb=XLSX.utils.table_to_book(document.querySelector(dom))//获取二进制字符串作为输出varwbout=XLSX.write(wb,{bookType:'xlsx',bookSST:true,type:'array'})try{FileSaver.saveAs(newBlob([wbout],{type:'application/octet-stream'}),excelTitle+'.xlsx')}catch(e){if(typeofconsole!=='undefined'){console.log(e,wbout)}}returnwbout}
4.使用函数---创建exports.vue文件
<!--组件都是elementui中的组件--><template><div><el-buttontype="info"style="margin:20px;"@click="exportExcelSelect">导出Excel</el-button><el-table:data="tableData"@selection-change="handleSelectionChange"><el-table-columntype="selection"></el-table-column><!--当数据为后端请求,形成分页后,组件实现分页记忆选中,该代码块替换上面代码部分<el-table:data="tableData":row-key="getRowKeys"@selection-change="handleSelectionChange"><el-table-column:reserve-selection="true"type="selection"></el-table-column>--><el-table-columnprop="date"label="日期"></el-table-column><el-table-columnprop="name"label="姓名"></el-table-column><el-table-columnlabel="详细地址"><el-table-columnprop="province"label="省份"></el-table-column><el-table-columnprop="city"label="市区"></el-table-column><el-table-columnprop="address"label="地址"></el-table-column><el-table-columnprop="zip"label="邮编"></el-table-column></el-table-column></el-table><el-dialogtitle="表格保存预览"width="70%":visible.sync="tableSavePreview"><el-table:data="multipleSelection"id="selectTable"height="380px"><el-table-columnprop="date"label="日期"></el-table-column><el-table-columnprop="name"label="姓名"></el-table-column><el-table-columnlabel="详细地址"><el-table-columnprop="province"label="省份"></el-table-column><el-table-columnprop="city"label="市区"></el-table-column><el-table-columnprop="address"label="地址"></el-table-column><el-table-columnprop="zip"label="邮编"></el-table-column></el-table-column></el-table><divslot="footer"class="dialog-footer"><el-buttontype="primary"@click="exportExcel">确定保存</el-button></div></el-dialog></div></template><script>importgetExcelfrom'存放exportsExcel.js文件的路径'exportdefault{name:"ExcelPage",data(){return{tableData:[{date:'2016-05-01',name:'王小红',province:'上海',city:'普陀区',address:'上海市普陀区金沙江路1518弄',zip:200333},{date:'2016-05-08',name:'王小华',province:'上海',city:'普陀区',address:'上海市普陀区金沙江路1518弄',zip:200333},{date:'2016-05-06',name:'王小丽',province:'上海',city:'普陀区',address:'上海市普陀区金沙江路1518弄',zip:200333},{date:'2016-05-07',name:'王小花',province:'上海',city:'普陀区',address:'上海市普陀区金沙江路1518弄',zip:200333}],multipleSelection:[],tableSavePreview:false,}},methods:{//当数据为后端请求,形成分页后,组件实现分页记忆选中getRowKeys(row){returnrow.id;},exportExcel(){getExcel('#selectTable','导出的自定义标题')},exportExcelSelect(){if(this.multipleSelection.length<1){this.$message.error('请选择要导出的内容!');returnfalse;}this.tableSavePreview=true;},handleSelectionChange(val){this.multipleSelection=val;}}}</script>
注:有不当之处还请谅解,欢迎交流。