java freemarker 生成图片_FreeMarker 生成 Word + 图片

Web开发经常遇到的需要,word 导出。

尝试使用过 Md2File、easypoi  国人的开源Jar  都很好用,但是不满足我的需求。

找了很多Word 的生成方式,最后选择 FreeMarker 。

如发现不对或可优化的的地方请留言我及时更正,以下记录本次功能开发的过程。

word 模板制作

1914c34f36eeb11c671bfdd9818960ad.png

先来一个简单的表格, ${reportName} = 我们要替换的变量

word 转 word 2003 xml

384c5a24ac347fe9f930e20a70bbdaba.png

xml 解析

将xml 文件 格式化一下,方便查看。xml格式化 百度

将文件 poi.xml 后缀名“xml”修改为“ftl”

OK的模板数据

ec343af81625d14ff0f69dc15e5ccf4e.png

需要调整的,${username} 关键字被分开了,需要手动调整成上图的样子

fa709c3937581382199f36bea50d0a2e.png

代码实现

public void wordExport () throws IOException {

configuration = new Configuration();

configuration.setDefaultEncoding("utf-8");

// 要填入模本的数据文件

Map dataMap = new HashMap();

dataMap.put("reportName", "张三");

// 设置模本装置方法和路径

File templePath = new File("d:/word/test/");

configuration.setDirectoryForTemplateLoading(templePath);

Template t = null;

try {

// temple.ftl为要装载的模板

t = configuration.getTemplate("poi.ftl");

t.setEncoding("utf-8");

} catch (IOException e) {

e.printStackTrace();

}

// 输出文档路径及名称

File outFile = new File("D:/word/test/"+new Date().getTime()+".doc");

Writer out = null;

try {

out = new BufferedWriter(new OutputStreamWriter(

new FileOutputStream(outFile), "utf-8"));

} catch (Exception e1) {

e1.printStackTrace();

}

try {

t.process(dataMap, out);

out.close();

} catch (TemplateException e) {

e.printStackTrace();

} catch (IOException e) {

e.printStackTrace();

}

}

36770f053b3531726d2779d977df4325.png

*表格数据循环

使用表达式

表格头xml

${test.name1}

${test.name2}

${test.name3}

${test.name4}

表格尾xml

#list>

3d1a0626db6a3b738e58653baebc7409.png

上图中表格循环5次显示,均测试数据。

ca7bb6036c023b19b327cc942765b616.png

实现代码

private void getData(Map dataMap) {

dataMap.put("reportName", "张三");

//dataMap.put("resPic", getImageStr());

//dataMap.put("flawPic", getImageStr());

List> testList= new ArrayList<>();

for(int i=1;i<=5;i++){

Map map=new HashMap<>();

map.put("name1", "我是小米"+i);

map.put("name2", "你好"+i);

map.put("name3", "老大"+i);

map.put("name4", "小强"+i);

testList.add(map);

}

dataMap.put("testList",testList);

}

生成的word 效果图

42d533d90ba1f08f739f1a2a0a1ce3fe.png

插入图片

基本和以上流程一样,

模板中插入照片,在xml中替换图片的base64值,代码写入新图片的base64值。

因我的word 中没图片就不提供代码了。

大家可以参考下面链接

参考文献

http://my.oschina.net/liweigov/blog/63868

http://blog.csdn.net/myfmyfmyfmyf/article/details/42641677

http://blog.csdn.net/myfmyfmyfmyf/article/details/36177979

http://blog.csdn.net/thismonth/article/details/5194982

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值