vue中向docx模板填充数据并下载以及docx文件预览
一、向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>
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
· 25岁的心里话