Java实现word模板导出

647 阅读1分钟

一:制作模板

1.设置参数

image.png

2.文件另存为

image.png 将文件另存为xml文件

3.文件格式化

格式化代码后修改错误

image.png 修改为:

image.png

4.修改文件后缀

.xml文件修改为 .ftl文件

5.将制作好的模板放到项目中

image.png

二:导出模板(Java代码编写)

//加载模板
TemplateEngine engine = TemplateUtil.createEngine(new TemplateConfig("templates", TemplateConfig.ResourceMode.CLASSPATH));
Template template = engine.getTemplate("test.ftl");
//写入数据
Map<String, String> map = new HashMap<>();
map.put("name","张三");
map.put("age","18");
//生成本地文件
template.render(map,new File("d:/test.doc"));

图片展示:

image.png

注: 图片转成base64写入到map中

Map<String, String> map = new HashMap<>();
map.put("name","张三");
map.put("age","18");
map.put("image",Base64.encode(new File("D:/test.png")));

循环图片(ftl中)

<#list imageVos as image>
<w:pict>
    <w:binData w:name="${"wordml://0"+image_index+3+"00000"+image_index+1+".png"}" xml:space="preserve">${image}</w:binData>
    <v:shape id="图片 3" o:spid="_x0000_i1025" type="#_x0000_t75" style="height:400;widtht:400;visibility:visible;mso-wrap-style:square"><v:imagedata src="${"wordml://0"+image_index+3+"00000"+image_index+1+".png"}"   o:title=""/></v:shape>
</w:pict>

注:

image_index 集合索引

image 数据

三:依赖的包

<dependency>
    <groupId>org.freemarker</groupId>
    <artifactId>freemarker</artifactId>
    <version>2.3.28</version>
</dependency>

<dependency>
    <groupId>cn.hutool</groupId>
    <artifactId>hutool-all</artifactId>
    <version>5.3.4</version>
</dependency>

四:freemarker网站

freemarker.foofun.cn/