1. 程式人生 > 實用技巧 >匯出word

匯出word

import { Message } from 'element-ui';
const docxtemplater = require('docxtemplater')
const PizZip = require('pizzip');
const JSZipUtils = require('jszip-utils');
const saveAs = require('file-saver').saveAs;
const base64DataURLToArrayBuffer = (dataURL:any) => {
  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 * @param {*} templateUrl 模板檔案路徑 * @param {*} fileName 匯出檔名稱 * @param {*} data 模板資料 */ const exportWord
= (templateUrl: string, fileName: string, data: any, userOption: any = {}) => { const ImageModule = require('open-docxtemplater-image-module'); JSZipUtils.getBinaryContent(templateUrl, (error: any, content: any) => { if (error) { Message.warning('沒有找到檔案模板,無法匯出!'); throw error; } const zip = new PizZip(content); let opts:any = {}; opts.centered = true; // 圖片居中,在word模板中定義方式為{%%image} opts.fileType = 'docx'; opts.getImage = (dataURL:any) => { return base64DataURLToArrayBuffer(dataURL); }; opts.getSize = (img: any, tagValue: any, tagName: string) => { return [600, 400]; }; opts = Object.assign(opts, userOption); const imageModule = new ImageModule(opts); const doc = new docxtemplater().attachModule(imageModule).loadZip(zip); doc.setData(data); try { // 用模板變數的值替換所有模板變數 doc.render(); } catch (error) { // 丟擲異常 const e = { message: error.message, name: error.name, stack: error.stack, properties: error.properties }; console.log(JSON.stringify({ error: e })); throw error; } // 生成一個代表docxtemplater物件的zip檔案(不是一個真實的檔案,而是在記憶體中的表示) const out = doc.getZip().generate({ type: 'blob', mimeType: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' }); console.log(out); // 將目標檔案物件儲存為目標型別的檔案,並命名 saveAs(out, `${fileName}.doc`); }); }; export default exportWord;