1、在package.json中添加安装包,并运行 npm install安装
{
"file-saver": "^2.0.5",
"html-docx-js": "^0.3.1"
}
2、在vue文件中使用
// 引用部分
import htmlDocx from 'html-docx-js/dist/html-docx';
import saveAs from 'file-saver';
//...........
// 导出方法
exportClick() {
// this.createExportModul()返回字符串拼接的html
this.createHtml = this.createExportModul()
const page = `<!DOCTYPE html><html><head><meta charset="UTF-8"></head><body> ${this.createHtml} </body></html>`;
let converted = htmlDocx.asBlob(page);
// 用 FielSaver.js里的保存方法 进行输出
saveAs(converted, `${this.title}.docx`);
}
优点:导出的文件中可以包含前端动态生成的一些图片,例如把echart图表中的信息需要在导出文件中显示,此时该导出功能必须由前端进行导出
缺点:生成文档的样式调整是由拼接字符串的行内样式起作用的
// 获取echarts图表中的png图片方法
const imgUrl = this.myChart.getDataURL('png')
// 将获取到的base64格式的图片拼接至字符串信息中
html += `<div style="text-align: center;">
<img class="chartImg" src="${imgUrl}" style="margin-left: 50%;transform: translate(-50%, 0);">
</div>`