一、安裝依賴
//1、docxtemplaternpm install docxtemplater pizzip -S//2、jszip-utilsnpm install jszip-utils -S//3、pizzipnpm install pizzip -S//4、FileSaver
npm install file-saver --save
二、創建word模版
也就是編輯一個word文檔,文檔中需要動態取值的地方用{變量}取值;表格數據可以進行循環,以{#數組變量名}開始,以{/數組變量名}結束,如果數組變量是字符串而非對象則{#table}{.}{/table}。圖片以{%圖片base64變量名}展示,{%%圖片base64變量名}表示圖片居中。word模版放在public下。
word模版占位符用法
三、導出方法
//導入包
import PizZip from 'pizzip'
import docxtemplater from 'docxtemplater'
import JSZipUtils from 'jszip-utils'
import { saveAs } from 'file-saver'data() {return {form: {userName: "杰克",value: "666", },// 表格信息tableData: [],//圖片img1: '',img2: ''};
},methods:{
// 導出echarts圖片,格式轉換,官方自帶,不需要修改
base64DataURLToArrayBuffer(dataURL) {const base64Regex = /^data:image\/(png|jpg|svg|svg\+xml);base64,/;if (!base64Regex.test(dataURL)) {return false;}const stringBase64 = dataURL.replace(base64Regex, "");let binaryString;if (typeof window !== "undefined") {binaryString = window.atob(stringBase64);} else {binaryString = new Buffer(stringBase64, "base64").toString("binary");}const len = binaryString.length;const bytes = new Uint8Array(len);for (let i = 0; i < len; i++) {const ascii = binaryString.charCodeAt(i);bytes[i] = ascii;}return bytes.buffer;
},
// 點擊導出word
exportWord() {//這里要引入處理圖片的插件,下載docxtemplater后,引入的就在其中了var ImageModule = require('docxtemplater-image-module-free');var fs = require("fs");const expressions = require("angular-expressions");let _this = this;// 讀取并獲得模板文件的二進制內容,放在項目中即可(wordTemplate.docx是public文件下的word模版)JSZipUtils.getBinaryContent("wordTemplate.docx", function(error, content) {if (error) {throw error;};expressions.filters.size = function (input, width, height) {return {data: input,size: [width, height],};};function angularParser(tag) {const expr = expressions.compile(tag.replace(/’/g, "'"));return {get(scope) {return expr(scope);},};}// 圖片處理let opts = {}opts = { centered: false };opts.getImage = (chartId)=> {return _this.base64DataURLToArrayBuffer(chartId);}opts.getSize = function(img, tagValue, tagName) {console.log(tagName)//自定義指定圖像大小,此處可動態調試各別圖片的大小if (tagName === "chartImg1") return [249,200];return [300,200];}// 創建一個PizZip實例,內容為模板的內容let zip = new PizZip(content);// 創建并加載docxtemplater實例對象let doc = new docxtemplater();// 去除未定義值所顯示的undefineddoc.setOptions({nullGetter: function() { return ""; }});doc.attachModule(new ImageModule(opts));doc.loadZip(zip);// 設置模板變量的值(鍵是word模版中用的值,值是vue文件data中的變量)doc.setData({..._this.form,table: _this.tableData,img1: _this.img1,img2: _this.img2});try {// 用模板變量的值替換所有模板變量doc.render();} catch (error) {// 拋出異常let e = {message: error.message,name: error.name,stack: error.stack,properties: error.properties};console.log(JSON.stringify({ error: e }));throw error;}// 生成一個代表docxtemplater對象的zip文件(不是一個真實的文件,而是在內存中的表示)let out = doc.getZip().generate({type: "blob",mimeType:"application/vnd.openxmlformats-officedocument.wordprocessingml.document"});// 將目標文件對象保存為目標類型的文件,并命名saveAs(out, "測試.docx");});
},
}
ECHARTS圖表的圖片并轉為base64格式,在圖表加載完成時
this.img2 = myChart2.getDataURL({pixelRatio: 2, // 導出的圖片分辨率比例,默認為 1。backgroundColor: '#fff' // 導出的圖片背景色,默認使用 option 里的 backgroundColor
});
如果是需要動態添加的背景圖,可以直接將圖片的base64碼賦值給img1變量。