根据项目需求,通过dom元素将页面导出成word文档,支持word文档的查看和编辑,(来人,直接上代码)
1 先下载html-docx-js依赖,官网html-docx-js
npm i html-docx-js
2 在进行下载file-saver,将文件进行本地下载
npm i file-saver
3 页面内使用下载的依赖
import { saveAs } from "file-saver";
import htmlToDocx from "html-docx-js/dist/html-docx";
4 代码演示(注意一定要写行内样式 不然导出来的样式不生效)
<template>
<div class="report-box" ref="reportRef">
<h2 style="text-align: center">分析报告</h2>
</div>
</template>
<script>
import { saveAs } from "file-saver";
import htmlToDocx from "html-docx-js/dist/html-docx";
export default {
methods: {
handelExprot() {
// 获取需要转换的dom元素
const sectionContent = this.$refs.reportRef.innerHTML;
// 使用html-docx-js插件将转换的dom引入插件中
const converted = htmlToDocx.asBlob(sectionContent);
// 使用file-saver 插件进行本地下载
saveAs(converted, "exported-document.docx");
},
},
}
</script>