一、向docx模板填充數據並下載
1.安裝對應依賴
cnpm install docxtemplater pizzip --save-dev cnpm install jszip-utils --save cnpm install jszip --save cnpm install file-saver --save
2.導入依賴包
import Docxtemplater from 'docxtemplater' import PizZip from 'pizzip' import JSZipUtils from 'jszip-utils' import {saveAs} from 'file-saver'
3.定義函數封裝方法
/** 4. 導出docx 5. @param { String } tempDocxPath 模板文件路徑 6. @param { Object } data 文件中傳入的數據 7. @param { String } fileName 導出文件名稱 */ exportDocx(tempDocxPath, data, fileName){ // 讀取並獲得模板文件的二進制內容 JSZipUtils.getBinaryContent(tempDocxPath, (error, content) => { if (error) { throw error } const zip = new PizZip(content) const doc = new Docxtemplater().loadZip(zip) doc.setData(data) try { // render the document (replace all occurences of {first_name} by John, {last_name} by Doe, ...) doc.render() } catch (error) { const e = { message: error.message, name: error.name, stack: error.stack, properties: error.properties } console.log({ error: e }) // The error thrown here contains additional information when logged with JSON.stringify (it contains a property object). throw error } const out = doc.getZip().generate({ type: 'blob', mimeType: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' }) // Output the document using Data-URI //下載文件 saveAs(out, fileName) // 這里如需預覽,可使用window.URL.createObjectURL(this.out)將blob轉為預覽路徑 }) }
4.使用
4.1 首先將准備的模板文件放到static下
4.2 調用
this.exportDocx('/test.docx', {nickName:'小明同學'}, '測試.docx')
這里如果報下面這個錯的話,一般是模板文件的路徑錯誤導致。vue-cli版本如果是2,則應該有一個static的文件夾,將你的模板文件放入這個static文件夾中;如果是3,則有一個public文件夾,將模板文件放入這個public文件夾中。
二、docx文件預覽
1.安裝對應依賴插件
cnpm i docx-preview
2.引入所需js,可下載放在public目錄下
<script src="https://unpkg.com/jszip/dist/jszip.min.js"></script>
3.使用
<template> <div class="home"> <div ref="file"></div> </div> </template> <script> import axios from 'axios' let docx = require('docx-preview'); export default { mounted(){ axios({ method: 'get', responseType: 'blob', // 設置響應文件格式 url: '/docx', //對應文件路徑 }).then(({data}) => { docx.renderAsync(data,this.$refs.file) // 渲染到頁面預覽 }) } } </script>