用freemarker生成word模板
需求:
给文书统一生成一个搞头文件,文件内容基本是一样的。
用freemarker生成docx文档
一、生成一个docx结尾的word模板,然后把文档的后缀docx改成zip,zip里会有生成很多文件。如下图:
然后打开word文件夹,如下图:
把document.xml拿出来,把后缀xml改成ftl,然后把里面的内容(在线格式化xml)格式化一下,把一些可变的参数做成变量。
二、在resources文件夹下创建wordTemplates文件夹,里面放刚才的zip和改名的gtwj.ftl文件。
三、替换word模板类:
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;import java.io.*;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;public class ZipUtils {private static final Logger logger = LoggerFactory.getLogger(ZipUtils.class);/*** 替换document , header1** @param zipInputStream zip文件的zip输入流* @param zipOutputStream 输出的zip输出流* @param bodyOs 要替换的 word内容流*/public static void replaceItem(ZipInputStream zipInputStream, ZipOutputStream zipOutputStream,ByteArrayOutputStream bodyOs) {String bodyname = "word/document.xml";//if (null == zipInputStream || null == zipOutputStream || null == bodyOs ) {return;}ZipEntry entryIn;try {while ((entryIn = zipInputStream.getNextEntry()) != null) {String entryName = entryIn.getName();ZipEntry entryOut = new ZipEntry(entryName);// 只使用 namezipOutputStream.putNextEntry(entryOut);if (entryName.equals(bodyname)) {// 使用替换流 替换word内容byte[] buf = bodyOs.toByteArray();zipOutputStream.write(buf,0,buf.length);}else {// 缓冲区byte[] buf = new byte[8 * 1024];int len;// 输出普通Zip流while ((len = (zipInputStream.read(buf))) > 0) {zipOutputStream.write(buf, 0, len);}}// 关闭此 entryzipOutputStream.closeEntry();}} catch (IOException e) {logger.error("zip文件的zip输入流失败:", e);} finally {close(bodyOs);close(zipInputStream);close(zipOutputStream);}}/*** 包装输入流*/public static ZipInputStream wrapZipInputStream(InputStream inputStream) {ZipInputStream zipInputStream = new ZipInputStream(inputStream);return zipInputStream;}/*** 包装输出流*/public static ZipOutputStream wrapZipOutputStream(OutputStream outputStream) {ZipOutputStream zipOutputStream = new ZipOutputStream(outputStream);return zipOutputStream;}private static void close(InputStream inputStream) {if (null != inputStream) {try {inputStream.close();} catch (IOException e) {logger.error("关闭流失败:", e);}}}private static void close(OutputStream outputStream) {if (null != outputStream) {try {outputStream.flush();outputStream.close();} catch (IOException e) {logger.error("关闭流失败:", e);}}}/*** 获取绝对路径* @return*/public static String systemUrl(){if(System.getProperties().getProperty("os.name").toUpperCase().indexOf("WINDOWS") != -1){return "D:";}return "/temp";}public static void wordAndDoc(Map<String, Object> dataMap,ByteArrayOutputStream byteArrayOutputStream) throws IOException {//word bodyString bodyName = "gtwjtest.ftl";ByteArrayOutputStream bodyOs = writeFile(bodyName,dataMap);ZipInputStream zipInputStream = ZipUtils.wrapZipInputStream(ZipUtils.class.getResourceAsStream("/wordTemplates/gtwj.zip"));ZipOutputStream zipOutputStream = ZipUtils.wrapZipOutputStream(byteArrayOutputStream);ZipUtils.replaceItem(zipInputStream, zipOutputStream, bodyOs);}public static void word(Map<String, Object> dataMap,ByteArrayOutputStream byteArrayOutputStream) throws IOException {//word bodyString bodyName = "gtwj.ftl";ByteArrayOutputStream bodyOs = writeFile(bodyName,dataMap);ZipInputStream zipInputStream = ZipUtils.wrapZipInputStream(ZipUtils.class.getResourceAsStream("/wordTemplates/gtwj.zip"));ZipOutputStream zipOutputStream = ZipUtils.wrapZipOutputStream(byteArrayOutputStream);ZipUtils.replaceItem(zipInputStream, zipOutputStream, bodyOs);}public static String wordFile(Map<String, Object> dataMap,String docxUrl) throws IOException {String bodyName = "gtwj.ftl";ByteArrayOutputStream bodyOs = writeFile(bodyName,dataMap);ZipInputStream zipInputStream = ZipUtils.wrapZipInputStream(ZipUtils.class.getResourceAsStream("/wordTemplates/gtwj.zip")); //D:\zip\月度用电报告.zipZipOutputStream zipOutputStream = ZipUtils.wrapZipOutputStream(new FileOutputStream(new File(docxUrl)));ZipUtils.replaceItem(zipInputStream, zipOutputStream, bodyOs);return docxUrl;}/*** @Description 生成带数据的模板* @Param*/public static ByteArrayOutputStream writeFile(String templateName,Map<String, Object> dataMap) throws IOException {Configuration configuration = new Configuration(Configuration.VERSION_2_3_28);configuration.setClassForTemplateLoading(ZipUtils.class, "/wordTemplates/");Template template = configuration.getTemplate(templateName);ByteArrayOutputStream os = new ByteArrayOutputStream();Writer out = new BufferedWriter(new OutputStreamWriter(os),10240);try {template.process(dataMap,out);} catch (TemplateException e) {logger.error("生成带数据的模板失败:", e);}finally {if(out != null ){out.close();}}return os;}/*** @Description 生成带数据的模板* @Param*/public static void writeFile(String outFilePath,String templateName,Map<String, Object> dataMap) throws IOException {Configuration configuration = new Configuration(Configuration.VERSION_2_3_28);configuration.setClassForTemplateLoading(ZipUtils.class, "/ftl");Template template = configuration.getTemplate(templateName);File docFile = new File(outFilePath);FileOutputStream fos = new FileOutputStream(docFile);Writer out = new BufferedWriter(new OutputStreamWriter(fos),10240);try {template.process(dataMap,out);} catch (TemplateException e) {logger.error("生成带数据的模板失败:", e);}finally {if(out != null ){out.close();}}}/*** @Description 判断文件夹是否存在 不存在就创建* @Param:* @return:*/private static void isChartPathExist(String dirPath) {File file = new File(dirPath);if (!file.exists()) {file.mkdirs();}System.out.println(file.exists()+" dirPath "+dirPath);}public static void main(String[] args) {
// String templatePath =ZipUtils.class.getResource("/").getPath()+ "/ftl";
// System.out.println(templatePath);
// isChartPathExist("D:\\zip\\123");File file = new File("F:\\word\\gtwj.pdf");if(file.exists()){if(file.isFile()){boolean b = file.delete();if (b) {logger.info("成功");}}}}
}
四、项目里引入jar包如下:
<dependency><groupId>org.freemarker</groupId><artifactId>freemarker</artifactId><version>2.3.28</version></dependency>
五、我用到的方法 ZipUtils.word(map, byteArrayOutputStream);其中map就是变量。
用freemarker生成word模板相关推荐
- freemarker生成word模板
freemarker生成word模板 一.引入依赖 <dependency><groupId>org.freemarker</groupId><artifac ...
- Java实现freemarker生成word模板
博主在做的是将word源文件中的内容读取出来,然后按照固定的格式输出,当然,源文件有大量,所以编写了程序来批量自动生成目标文件. 本文要介绍的就是如何生成模板,并将从源文件截取的内容填充到模板文件(即 ...
- Freemarker 生成word 模板文件
2019独角兽企业重金招聘Python工程师标准>>> /*** * word 下载生成 * @param positionvo * @return ...
- spring使用freemarker生成word文档包含表格、图片(循环插入)
spring使用freemarker生成word文档包含表格.图片(循环插入) 效果图 因为测试数据是重复的,所以显示都是重复的数据,替换导入map中的数据可以显示不重复的数据. 操作步骤 1,创建一 ...
- 用freemarker生成word文档,并插入图片
用freemarker生成word文档,并插入图片 最近需要做一个问卷功能,要求用户填写完问卷后,后台会生成一个word文档,将用户提交的数据插入到word中. 创建word模板 新建一个word文档 ...
- Java使用freemarker生成word文档并转pdf文档
Java使用freemarker生成word文档后转pdf 先来看看效果图 进入正题 项目需求: 为订单后生成对应的pdf文档,文档内包含图片. 方案一:使用freemarker和itext把html ...
- 使用FreeMarker生成word文档(带图片),word转pdf,预览pdf,pdf下载工具类
一.下载或配置: 下载jar包 :freemaker的jar包下载 下载jar包 :aspose-words的jar包下载 或者配置maven依赖: pom.xml添加aspose的依赖包(maven ...
- Freemarker生成word文件,打开后页眉和页脚图片不显示
Freemarker生成word文件,打开后页眉和页脚图片不显示 在我们开发过程中通常会把模板文件Ctrl+Alt+L格式化,方便处理.这样就造成word的标签格式产生多余的换行或者空白,但是word ...
- Java使用freemarker生成word文件
首先声明我的项目是一个web项目,生成的word文件直接通过response响应发送给前端.如果不是web项目的话可以像网上的其他教程一样将生成的word保存在本地. 要利用freemarker生成w ...
最新文章
- 算法杂货铺——分类算法之朴素贝叶斯分类(Naive Bayesian classification)
- java生成16位随机数_java中如何产生一个16位数字组成的随机字符串?谢谢各位了...
- 【PHP】最详细PHP从入门到精通(一)
- 用JAVA不失精度计算等额本息还款列表
- 分布式电商项目——10.商品搜索 springboot 集成ES+kibana+logstash+Ik分词器+Ik拼音分词器
- 给 Vuepress 和 ElementUI 添加夜间暗色模式
- 0x00F749F6 处(位于 基于多态实现职工管理系统.exe 中)引发的异常: 0xC0000005: 读取位置 0x00000004 时发生访问冲突。
- 关于半岛体试验的一些知识汇总
- 如果不能从做事转入治人,那么经年的螺丝钉岁月,会让你既无暇提高自己,也无法积累资源,在锈迹斑斑以后被新的螺丝钉换掉。
- 数据库设计1-数据库设计简述
- 利用 FFMPEG 批量提取指定起止时间视频片段
- springboot整合mybatis
- 淘宝天猫整店店铺商品API,店铺商品分类接口代码教程
- SAS学习步骤和参考书
- [环保] 为了反击无耻的两桶油雇来的砖家,三伏天,我一个月开车不开空调测油耗
- VUE项目--卖座app
- mac php安装扩展名,Mac自带的php怎么安装扩展
- 当电视成为“一台屏幕变大的智能手机”,客厅又成为争夺目标
- 【论文复现3】算法2——Clustered sampling based on model similarity
- Linux系统USB驱动目录,Linux那些事儿之我是USB 目录
热门文章
- Codeforces 1462 A. Favorite Sequence
- Buildroot 移植 telnetd 到 Jz2440
- 计算机视觉-相机标定(Camera Calibration)
- July Challenge 2017 | Whats in the Name
- Linux系统中安装和管理程序 太详细了
- RAG:Retrieval-Augmented Generation for Knowledge-Intensive NLP Tasks 论文阅读
- 计算机数字信号原理,数字滤波器是什么?数字滤波器的工作原理
- rapid:实现jsp页面代码的复用
- 大领导在酒桌上当着小领导面数落我什么意思?四个招数不得不服
- RIL 机制---开篇