首先需要导入的插件有:
npm install element-plus --save,//elementplus的组件库(这个可用可不用,我用的是组件的按钮所以需要使用到他)
npm install xlsx --save//xlsx的插件
现在看看代码吧
<script setup> import { reactive, ref } from "vue"; import XLXS from "xlsx"; import FileSaver from "file-saver"; defineProps({ msg: String, }); const count = ref(0); const state = reactive({ excelTitle: "表格标题1", }); const tableData = reactive([ { 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 路", }, ]); const exportClick = () => { // 设置当前日期 let time = new Date(); let year = time.getFullYear(); let month = time.getMonth() + 1; let day = time.getDate(); let name = year + "" + month + "" + day; // 导出文件名 const filename = state.excelTitle; // 通过id,获取导出的表格数据 const wb = XLXS.utils.table_to_book(document.getElementById("table"), { raw: true, }); const wbout = XLXS.write(wb, { bookType: "xlsx", bookSST: true, type: "array", }); try { FileSaver.saveAs( new Blob([wbout], { type: "application/octet-stream", }), name + ".xlsx" ); } catch (e) { console.log(e); } return wbout; }; </script> <template> <div class="home"> <button type="button" @click="exportClick()">导出pdf</button> <div id="table"> <el-table :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> </div> </div> </template> <style scoped> #pdfDom { color: #42b983; } </style>