2025.08.23今天我学习了如何将html页面内容导出到word中,并保持原有格式,效果如下:
一、安装插件
npm install file-saver
npm install html-docx-js
二、代码如下:
<template>
<div>
<el-button @click="exportToWord">生成报表</el-button>
<div style="width:600px;border:1px solid red" id="table">
<div v-html="demo"/>
<div id="main" style="width: 100%;height:400px;"/>
</div>
</div>
</template>
<script>
import htmlDocx from "html-docx-js/dist/html-docx";
import saveAs from 'file-saver';
export default {
data() {
return {
demo: '',//存放html数据
imgSrc: '',//存放图片
};
},
async mounted() {
this.demo = '<p>已为你生成以下表格数据:</p>\n' +
'<table border="1" class="table_style">\n' +
' <thead>\n' +
' <tr>\n' +
' <th>名称</th>\n' +
' <th>时间</th>\n' +
' <th>患者数量</th>\n' +
' </tr>\n' +
' </thead>\n' +
' <tbody>\n' +
' <tr>\n' +
' <td>xxx学科</td>\n' +
' <td>20250720</td>\n' +
' <td>0</td>\n' +
' </tr>\n' +
' <tr>\n' +
' <td>合计</td>\n' +
' <td>总计</td>\n' +
' <td>0</td>\n' +
' </tr>\n' +
' </tbody>\n' +
'</table>\n' +
'<h3>分析</h3>\n' +
'<ul>\n' +
' <li><strong>时间段变化趋势</strong>:仅一个时间点,无法分析趋势。</li>\n' +
' <li><strong>异常点分析</strong>:患者数量为 0,需核实。</li>\n' +
'</ul>'
this.initChart();//初始化图表
},
methods: {
//初始化图表
initChart() {
let myChart = this.$echarts.init(document.getElementById('main'));
let option = {
xAxis: {
show: true,
data:['20250819','20250820','20250821','20250822','20250823','20250824']
},
yAxis: {
show: true
},
tooltip:{
show:true
},
series: [
{
type: 'bar',
data: [10, 20, 30,40,50,60]
}
]
};
myChart.clear();
myChart.resize();
myChart.setOption(option);
// 初始化生成图片
setTimeout(()=>{
this.imgSrc = myChart.getDataURL({
type: 'png',
pixelRatio: 1,
backgroundColor: '#fff'
})
},1000)
},
// 生成word文档
async exportToWord() {
let contentHtml = document.getElementById("table").innerHTML;
contentHtml += '<img src="' + this.imgSrc + '" width="556"/>';
let cssHTML = `
.table_style{
border-collapse: collapse;
width: 100%;
text-align: left;
overflow: auto;
background-color: #f8f9fa;
}
.table_style th,
.table_style td {
padding: 10px;
font-size: 15px;
border: 1px solid #ddd;
text-align: center;
}
.table_style th {
font-weight: bold;
}`
let content = `
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<style>
${cssHTML}
</style>
</head>
<body>
${contentHtml}
</body>
</html>`;
let converted = htmlDocx.asBlob(content);
saveAs(converted, "测试导出.docx");
},
}
}
</script>
<style>
.table_style{
border-collapse: collapse;
width: 100%;
text-align: left;
overflow: auto;
background-color: #f8f9fa;
}
.table_style th,
.table_style td {
padding: 10px;
font-size: 15px;
border: 1px solid #ddd; /* 单元格内边框 */
text-align: center; /* 居中对齐 */
}
.table_style th {
font-weight: bold;
}
</style>