直接上图
点击打印按钮,直接调用浏览器的打印预览功能
在预览功能中可以设置表格的样式以及字段等
上代码
<template>
<div>
<el-button style="text-align: left" type="success" @click="printTable">打印表格</el-button>
<el-table :data="tableData">
<!--表格内容-->
</el-table>
</div>
</template>
封装好的 printToTable.js 放在文章的最下方
<script>
import { printToTable } from '@/assets/js/PrintToTable'
import axios from 'axios'
export default {
data () {
return {
// 后端请求的数据
tableData: []
}
},
mounted () {
this.queryList()
},
methods: {
queryList () {
axios.get('后端请求的接口')
.then((res) => {
if (res.data.code === 200) {
this.tableData = res.data.list
}
})
.catch((error) => {
console.log(error)
})
},
printTable () {
// 打印的表格内容
const tableContent = `
<table>
<thead>
<tr>
<th>序号</th>
<th>姓名</th>
<th>年龄</th>
<th>性别</th>
<th>部门</th>
<th>电话</th>
<th>创建时间</th>
<th>更新时间</th>
<th>状态</th>
</tr>
</thead>
<tbody>
${this.tableData.map(item => `
<tr>
<td>${item.id}</td>
<td>${item.username === null ? '' : item.username}</td>
<td>${item.age === null ? '' : item.age}</td>
<td>${item.sex === null ? '' : item.sex}</td>
<td>${item.department === null ? '' : item.department}</td>
<td>${item.phone === null ? '' : item.phone}</td>
<td>${item.createDate === null ? '' : item.createDate}</td>
<td>${item.updateDate === null ? '' : item.updateDate}</td>
<td>${item.status === null ? '' : item.status}</td>
</tr>
`).join('')}
</tbody>
</table>
`
const tableTitle = '信息表'
printToTable(tableContent, tableTitle)
}
}
}
</script>
printToTable.js 相关代码
export const printToTable = (tableContent, tableTitle) => {
// 创建一个新的窗口用于打印
const newWindow = window.open('', '_blank')
// 打印的表格样式
const tableStyle = `
<style>
table {
width: 100%;
height: 100%;
border-collapse: collapse;
}
td {
border: 1px solid black;
text-align: center;
min-width: 90px;
max-width: 150px;
/*max-height: 400px;*/
font-size: 14px;
}
th {
border: 1px solid black;
background-color: #be0000;
color: white;
}
.print-title {
font-size: 28px;
font-weight: bold;
text-align: center;
margin-bottom: 20px;
}
</style>
`
// 将表格内容写入新窗口中
newWindow.document.write('<html lang="en"><head><title>BTC</title>')
// newWindow.document.write('<html><head>')
newWindow.document.write(tableStyle)
newWindow.document.write('</head><body>')
newWindow.document.write(`<div class="print-title">${tableTitle}</div>`)
newWindow.document.write(tableContent)
newWindow.document.write('</body></html>')
// 打印新窗口中的内容
newWindow.print()
// 关闭新窗口
newWindow.close()
}