<template> <div> <el-button type="primary" @click="click">按钮</el-button> <div v-html="table"></div> </div> </template> <script> import form from "../components/form.vue" import { reactive, toRefs } from "vue"; // 输出base64编码 function base64(str) { return window.btoa(unescape(encodeURIComponent(str))) }; function createTable(fields, data) { const header = fields.map(({ label }) => `<td>${label}</td>`).join(""); const fieldsArr = fields.map(({ prop }) => prop); const body = data.map(dataItem => { const tds = fieldsArr.map(fieldItem => `<td>${dataItem[fieldItem]}</td>`).join("") return `<tr>${tds}</tr>` }).join(""); // Worksheet名 const worksheet = 'Sheet1'; const table = ` <table border="1" cellpadding="0"> ${header} ${body} </table>`; const template = ` <html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40" > <head> <!--[if gte mso 9]> <xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet> <x:Name>${worksheet}</x:Name> <x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet> </x:ExcelWorksheets></x:ExcelWorkbook></xml> <![endif]--> </head> <body> ${table} </body> </html>`; window.location.href = `data:application/vnd.ms-excel;base64,${base64(template)}`; return table; } export default { components: { myForm: form }, setup() { const state = reactive({ fields: [ { prop: "date", label: "Date" }, { prop: "name", label: "Name" }, { prop: "address", label: "Address" }, ], tableData: [ { date: '2016-05-03', name: 'Tom', address: 'No. 189, Grove St, Los Angeles', }, { date: '2016-05-02', name: 'Tom', address: 'No. 189, Grove St, Los Angeles', }, { date: '2016-05-04', name: 'Tom', address: 'No. 189, Grove St, Los Angeles', }, { date: '2016-05-01', name: 'Tom', address: 'No. 189, Grove St, Los Angeles', }, ], table: "", }); const click = () => { const table = createTable(state.fields, state.tableData); state.table = table; } return { ...toRefs(state), click, } } } </script>