vue +echarts+ docxtemplater 导出word页面(纯前端)

最近遇到一个将包含echarts图和Table的页面导出成word文档,研究了一下,决定使用docxtemplater 插件进行开发,整个思考的方向有以下几点:

  • 编写好word模板,具体的写法,可以参考https://docxtemplater.com/demo/#loop-table中demo,注意这个插件中很多的模板是要收费的(commercial),有一部分模板是免费的(带有free),简单的需求可以使用此插件。
  • 对于页面中的Table,只需要将要写入文档的数据整理成指定的样式,具体也可以参考https://docxtemplater.com/demo/#loop-table,注意word文档中所涵盖的字段名称要与传入的字段保持一致
  • 对于echarts图的写入,要借用开源的docxtemplater-image-module-free方法。首先,echarts图通过getDataURL()方法获取一个base64 的 URL,其次,利用docxtemplater-image-module-free官网中提供的base64DataURLToArrayBuffer()方法将base64的URL进行转换。

前期准备:

1、按照依赖的插件docxtemplaterjszip-utilsjszipFileSaver、docxtemplater-image-module-free

//-- 安装 docxtemplater
npm install docxtemplater pizzip  --save
//-- 安装 jszip-utils
npm install jszip-utils --save 
//-- 安装 jszip
npm install jszip --save
//-- 安装 FileSaver
npm install file-saver --save
//安装 docxtemplater-image-module-free
npm install --save docxtemplater-image-module-free 

2、引入依赖包

import docxtemplater from 'docxtemplater'
import PizZip from 'pizzip'
import JSZipUtils from 'jszip-utils'
import {saveAs} from 'file-saver'
import ImageModule from 'docxtemplater-image-module-free '

注,若引入docxtemplater-image-module-free 报错时,可尝试使用require方法引入。

let ImageModule = require('docxtemplater-image-module-free');

3、代码

// vue 页面
// echarts 图

// table-iview
// 导出按钮

 

4、参考链接

https://www.npmjs.com/package/docxtemplater-image-module-free

https://docxtemplater.com/demo/#loop-table

https://www.echartsjs.com/zh/api.html#echartsInstance.getDataURL

https://www.jianshu.com/p/b3622d6f8d98

https://www.jianshu.com/p/0de31429b12a

https://docxtemplater.readthedocs.io/en/latest/api.html#methods

补充一个踩过的坑~

在定义数据是,尤其是table数据时,字符串一定要用双引号!!!不然导出的文件可能没有数据

你可能感兴趣的:(js)