java用freemarker导出数据到word(含多图片)

一、制作word模版

新建word文档,按照需要设置好字体等各种格式;这里为了显得整齐使用了无边框的表格。

java用freemarker导出数据到word(含多图片)

将word文档另存为xml文件(注意不是word xml文档,我吃了这家伙的大亏了)

java用freemarker导出数据到word(含多图片)

然后用文本编辑器打开这个xml文件,将需要动态显示的文字替换为变量,如:${topicName},

图片需要1.将w:binData标签的一堆字符替换成将来包含图片字符的变量2.为了防止生成多图时出错,将v:shape标签的id属性、v:imagedata标签的src属性、w:binData标签的w:name属性替换为变量,这里变量可以像EL表达式一样写在字符串里面,使用形如${var_index}这样的表达式可以获取当前list遍历到的变量索引。

 <w:pict><w:binData w:name="wordml://${module_index}_${childModule_index}.png">${childModule.src}</w:binData><v:shape id="_x0000_s1026_${module_index}_${childModule_index}" o:spt="75" alt="${childModule.name}" type="#_x0000_t75" style="height:240pt;width:300pt;" filled="f" o:preferrelative="t" stroked="f" coordsize="21600,21600"><v:path/><v:fill on="f" focussize="0,0"/><v:stroke on="f" joinstyle="miter"/><v:imagedata src="wordml://${module_index}_${childModule_index}.png" o:title="${childModule.name}"/><o:lock v:ext="edit" aspectratio="t"/><w10:wrap type="none"/><w10:anchorlock/></v:shape></w:pict>

添加<#list></#list>标签的时候注意标签的位置,看清包含了哪些标签。代码多的快看花眼了(tbl害人啊),使用一个有高亮显示的编辑器何其重要!

搞定后后缀名改为ftl,放到项目中。

java用freemarker导出数据到word(含多图片)

二、bean配置,我用了官方文档的最简单配置

 <!-- freemarkerTemplate -->
<bean id="freemarkerConfig" class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer">
<property name="templateLoaderPath">
<value>classpath:/templates/freemarker/</value>
</property>
</bean>

三、controller组织数据

 @Resource(name="freemarkerConfig") private FreeMarkerConfigurer freemarkerConfig;

这里只贴过来了部分核心代码

 List<ModuleParam> moduleList = JSONObject.parseArray(json.get("parentList").toString(), ModuleParam.class);
String topicName = json.get("topicName").toString();
String topicId = json.get("topicId").toString();
String summarize = json.get("summarize").toString(); Map<String,Object> dataMap = new HashMap<String,Object>();
dataMap.put("moduleList", moduleList);
dataMap.put("topicName",topicName);
dataMap.put("summarizeContent",summarize);
 Configuration configuration = freemarkerConfig.getConfiguration();
configuration.setDefaultEncoding("UTF-8");
Template t=null;
t = configuration.getTemplate("reportTemplate.ftl");
File outFile = new File(fileName);
Writer out = null;
FileOutputStream fos=null;
try{
fos = new FileOutputStream(outFile);
out = new BufferedWriter(new OutputStreamWriter(fos,"UTF-8"));
t.process(dataMap, out);
}finally{
if(out != null){
out.close();
}
if(fos != null){
fos.close();
}
}

基本就这些啦~~

参考:

Java用freemarker导出word http://blog.csdn.net/wangqiuyun/article/details/26348819

Java多种方式动态生成doc文档:http://www.cnblogs.com/Joanna-Yan/p/5280272.html

推荐 :freemarker系列

上一篇:Arch Linux root密码忘记了怎么办


下一篇:Aravis 库编译方法