您的位置:首页 > 编程语言 > Java开发

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系列

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: