1. 程式人生 > 其它 >vue匯出元件--docxtemplater應用,支援匯出office檔案

vue匯出元件--docxtemplater應用,支援匯出office檔案

1.安裝依賴

  npm i docxtemplater -S
  npm i docxtemplater-image-module -S
  npm i pizzip -S
  npm i jszip-utils -S
  npm i file-saver -S

2.vue檔案引入依賴

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

3.vue需要實現的方法

exportdefault{ data(){ letself=this; return{ imageOpts:{ getImage(tagValue,tagName){//獲取base64格式圖片 returnself.base64DataURLToArrayBuffer(tagValue); }, getSize(img,tagValue,tagName){//返回圖片大小,長*寬 return[60,80]; } } } }, methods:{ //匯出檔案 export2Word(v,t,name){//v:圖片路徑,t:時間字串,name:匯出檔名稱--變數需自己定製,此處為舉例 letself=this; JSZipUtils.getBinaryContent( "***.docx",//需要匯出的模板檔案地址 function(error,content){ if(error){ throwerror; } letzip=newPizZip(content); letdoc=newdocxtemplater().loadZip(zip); doc.attachModule(newImageModule(self.imageOpts)); doc.setData({//設定模板資料 imgsrc:v, timestr:t }); try{ doc.render(); }catch(error){ lete={ message:error.message, name:error.name, stack:error.stack, properties:error.properties }; console.log(JSON.stringify({error:e})); throwerror; } letout=doc.getZip().generate({ type:"blob", mimeType:"application/vnd.openxmlformats-officedocument.wordprocessingml.document"//匯出檔案格式 }); saveAs(out,name+".docx"); } ); }, //獲取base64格式圖片 base64DataURLToArrayBuffer(dataURL){ constbase64Regex=/^data:image\/(png|jpg|svg|svg);base64,/; if(!base64Regex.test(dataURL)){ returnfalse; } conststringBase64=dataURL.replace(base64Regex,""); letbinaryString; if(typeofwindow!=="undefined"){ binaryString=window.atob(stringBase64); }else{ binaryString=Buffer.from(stringBase64,"base64").toString("binary"); } constlen=binaryString.length; constbytes=newUint8Array(len); for(leti=0;i<len;i++){ constascii=binaryString.charCodeAt(i); bytes[i]=ascii; } returnbytes.buffer; } } }

4.匯出檔案

5.模板說明

  {%img}圖片

  {#list}{/list}迴圈、if判斷

  {#list}{/list}{^list}{/list} if else

  {str}文字

  詳見:https://docxtemplater.readthedocs.io/en/latest/tag_types.html