java生成word之poi-tl代码学习

来源:互联网 发布:天下3魍魉捏脸数据 编辑:程序博客网 时间:2024/06/11 20:01

转载:http://11822658.blog.51cto.com/11812658/1796123

问题

通过Java语言在后台生成需要的word文档,供用户下载打印等。用Java操作word文档,毫无疑问,会用到apache poi,对于poi如何操作word文档,这里不作过多介绍。本文主要讲解如何通过一个制作好的word文件,通过数据填充,生成复杂样式的word。


关于poi-tl

poi-tl:poi template language 一个基于poi的word模板生成文档的开源组件。

文档介绍:http://deepoove.com/poi-tl/

GitHub地址:https://github.com/Sayi/poi-tl

代码地址:见github的junit测试用例 


通过poi-tl可以不了解具体细节,几行代码轻松实现word模板的填充,我们只需要获取对应数据,进行渲染即可。


Junit代码示例

1.首先在工程中引用poi-tl:

<dependency>    <groupId>com.deepoove</groupId>    <artifactId>poi-tl</artifactId>    <version>0.0.3</version></dependency>

2.制作word模板

根据模板标签语法

  • {{template}}

    普通文本,渲染数据为:String或者TextRenderData

  • {{@template}}

    图片,渲染数据为:PictureRenderData


word文档PB.docx 内容如下图:


wKioL1d71Z7BHE5SAAFlKD-icgI016.png-wh_50


3.Java main代码

        public static void main(String[] args) throws Exception {                //构造数据Map<String, Object> datas = new HashMap<String, Object>(){{put("header_version", "ver 0.0.3");put("logo", new PictureRenderData(100, 120, "src/test/resources/logo.png"));put("title", new TextRenderData("9d55b8", "Deeply in love with the things you love,\\n just deepoove."));put("changeLog", new TableRenderData(new ArrayList<RenderData>(){{add(new TextRenderData("d0d0d0", ""));add(new TextRenderData("d0d0d0", "introduce"));}},new ArrayList<Object>(){{add("1;add new # gramer");add("2;support insert table");add("3;support more style");}}, "no datas", 10600));put("website", "http://www.deepoove.com/poi-tl");}};                                //读取模板,进行渲染XWPFTemplate doc = XWPFTemplate.create("src/test/resources/PB.docx");RenderAPI.render(doc, datas);//输出渲染后的文件FileOutputStream out = new FileOutputStream("out.docx");doc.write(out);out.flush();out.close();}


4.查看out.docx文档内容

wKioL1d718iTlzubAACh792hN8Y634.png-wh_50


总结

可以看到,不需要关心任何word操作细节,只需要准备数据,渲染到标签语法制作的docx文档即可。


0 0