java用freemarker导出数据到word(含多图片)
2016-05-30 11:25
671 查看
一、制作word模版
新建word文档,按照需要设置好字体等各种格式;这里为了显得整齐使用了无边框的表格。
将word文档另存为xml文件(注意不是word xml文档,我吃了这家伙的大亏了)
然后用文本编辑器打开这个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,放到项目中。
二、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 https://www.geek-share.com/detail/2611556420.html
Java多种方式动态生成doc文档:https://www.geek-share.com/detail/2669303420.html
推荐 :freemarker系列
相关文章推荐
- Java核心知识点-JVM结构和工作方式
- java 集合练习题3
- Java中字符串String的常用分割方法
- 如何调优JVM - 优化Java虚拟机(大全+实例)
- Struts2综合应用实例--添加学生信息
- java创建对象时,new 出一个对象 和 = null的区别?
- Java中变量的内存分配
- Java课程设计
- 重装Eclipse遇到的一些问题
- struts2的interceptor总结
- Hadoop之——windows7+eclipse+hadoop2.5.2环境配置
- 享元模式(Flyweight)Java
- JAVA多功能通讯录第十三周
- 用JDK自带方法 写入XML文档
- java中jdbc链接数据库
- 将web项目导入到eclipse/MyEclipse中常见错误
- java中四种引用类型
- 再谈java枚举 ENUM
- springMVC+Hibernate 框架整合
- java 中的fanal