思路解说
- word 模板文件(doc 或 docx 文件)另存为 xml 文件
- 将后缀 xml 改成 html;大部分文档会改成 ftl(FreeMarker 的后缀名),因为 word 文件另存为 xml 文件后,xml 文件中的代码很乱,后面的修改会很麻烦,因为我习惯用 VSCode 编辑器,安装 Beautify 插件后,可以自动格式化 html 代码,这样有利于后面的修改
- 将内容用${param}替换;例:姓名:月牙坠-->姓名:${name}
- word 文件中的图片是 Base64 编码,我在这里封装了一个方法 imgUrl2Base64(图片地址转Base64编码) top.yueyazhui.word_freemarker.util.ExportDocUtil.getImageBase64
- 如果想要列表(表格)内容,在 html 文件中找到单个内容,在外层加
封装导出 word 文件到客户端的方法top.yueyazhui.word_freemarker.service.IExportDocService.exportDocToClient
html 中引用的数据源是一个Map类型,所以传递数据的时候需要把Object类型转成Map类型
word 原文件src/main/resources/attachment/info.doc
FreeMarker 配置
- #指定freemarker的模板路径和模板的后缀
- spring.freemarker.template-loader-path=classpath:/templates/
- spring.freemarker.suffix=.html
- # 指定字符集
- spring.freemarker.charset=utf-8
- # 指定是否要启用缓存
- spring.freemarker.cache=false
- #指定是否要暴露请求和会话属性
- spring.freemarker.expose-request-attributes=true
- spring.freemarker.expose-session-attributes=true
复制代码 FreeMarker 语法
- <#noparse>
- <#include "./common.ftl">
- </#noparse>
- <#if favorite.id == 5>
- <#break>
- </#if>
- <#switch sex>
- <#case 1>男<#break>
- <#case 0>女<#break>
- <#default>未知
- </#switch>
复制代码 前端(vue)
api
- import request from '@/utils/request'
- export function exportDoc() {
- return request({
- url: '/export/doc/',
- method: 'get',
- responseType: 'blob'
- })
- }
复制代码view
- import { exportDoc } from '@/api/**'
- exportDoc().then(res => {
- var fileNameEncode = res.headers['content-disposition'].split('filename=')[1]
- var fileName = decodeURIComponent(fileNameEncode)
- const blob = new Blob([res.data], {
- type: res.data.type
- })
- let link = document.createElement('a')
- link.style.display = 'none'
- let objectUrl = URL.createObjectURL(blob)
- link.href = objectUrl
- link.download = fileName
- link.click()
- URL.revokeObjectURL(objectUrl)
- })
复制代码注:axios 的响应拦截器
- // 二进制数据则直接返回
- if (res.request.responseType === 'blob') {
- return res
- }
复制代码 源码
word_freemarker
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作! |