填充数据到word模板中

来源:互联网 发布:单片机tssop28封装尺寸 编辑:程序博客网 时间:2024/06/04 23:22

昨天写了一篇博客,是导出word模板的。

今天来说一下如何填充数据到模板中。

先上图,合同:



需要在指定需要填充数据的位置,添加标识,这只是初步的标识,

然后,另存为xml格式,会发现,这些标识,可能会发生转义(因为字体,颜色,加粗,下划线等等因素)。如图下:



然后在xml文件中,找到对应标识的位置,改成如下格式。

${zpmc?if_exists}
修改后的为:



因为,可能由于数据的问题,某些字段数据并不存在,所以,要在后面加上    ?if_exists


然后,代码如下:

package com;import java.io.BufferedWriter;import java.io.File;import java.io.FileOutputStream;import java.io.OutputStreamWriter;import java.io.Writer;import java.util.HashMap;import java.util.Map;import freemarker.cache.FileTemplateLoader;import freemarker.cache.TemplateLoader;import freemarker.template.Configuration;import freemarker.template.Template;public class CreateWordT {public static void main(String[] args) {Map<String, Object> cont = new HashMap<String, Object>();// 存储数据cont.put("xmh", "111");cont.put("hth", "222");cont.put("zpmc", "");cont.put("zpsm", "444");cont.put("zpzs", "555");try {//模板的路径File fir = new File("W:/test/wswhr/");//生成文件的路径及文件名。File outFile = new File("W:/test/wswhr/委托创作合同.doc");Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile), "UTF-8"));// 使用FileTemplateLoader//指定模板路径TemplateLoader templateLoader = null;templateLoader = new FileTemplateLoader(fir);String tempname = "委托创作合同.xml";Configuration cfg = new Configuration();cfg.setTemplateLoader(templateLoader);Template t = cfg.getTemplate(tempname, "UTF-8");t.process(cont, out);out.flush();out.close();} catch (Exception e) {e.printStackTrace();}}}

代码中,t.process(cont,out);

会在模板t中,填充cont的数据,输出到out文件中。

成功后的结果如下:


因为作品名称,我没有放数据,所以为空。


0 0
原创粉丝点击