1.导入需要用到的jar包:
http://pan.baidu.com/s/1nujUwmX
2.用word编制模板:
3.将该模板保存为*.xml 的文件形式
接下来,上面写的拼音就起到作用了.
打开xml文件.搜索 title.
将BBTEST 改为 ${BBTEST}
其他地方一样的修改。
改完后,把文件的后缀名直接改成ftl。
4.代码如下:
package com.yabushan.test.util;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
public class WordTest {
public static void main(String[] args) {
WordTest test = new WordTest();
test.createWord();
}
private Configuration configuration = null;
public WordTest(){
configuration = new Configuration();
configuration.setDefaultEncoding("UTF-8");
}
public void createWord(){
Map<String,Object> dataMap=new HashMap<String,Object>();
getData(dataMap);
System.out.print(this.getClass());
configuration.setClassForTemplateLoading(this.getClass(), "/com/yabushan/test/util"); //FTL文件所存在的位置
Template t=null;
try {
t = configuration.getTemplate("test.ftl"); //文件名
} catch (IOException e) {
e.printStackTrace();
}
File outFile = new File("E:/"+Math.random()*10000+"BB.doc");
Writer out = null;
try {
out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile)));
} catch (FileNotFoundException e1) {
e1.printStackTrace();
}
try {
t.process(dataMap, out);
} catch (TemplateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private void getData(Map<String, Object> dataMap) {
dataMap.put("BBTEST", "标题");
dataMap.put("nian", "2016");
dataMap.put("yue", "3");
dataMap.put("ri", "12");
dataMap.put("shenheren", "发哥哥");
dataMap.put("dianhua", "13020265912");
dataMap.put("bianzhi", "CEO");
List<Map<String,Object>> list = new ArrayList<Map<String,Object>>();
for (int i = 0; i < 1000; i++) {
Map<String,Object> map = new HashMap<String,Object>();
map.put("xuhao", i);
map.put("neirong", "内容"+i);
list.add(map);
}
dataMap.put("list", list);
}
}
5.
在刚刚的那个ftl文件中直接编辑:
打开FTL文件,搜索 <w:tr
找到第一个,tr的意思不用解释了吧,代表着一行。
这也意味着我找到了Table中的第一行,但是我需要遍历的不是从第一行开始,而是从第二行。
好的,继续搜索,找到第二个。
在它的头上加一个<#list 你的集合名称 as xxxx>
ok,有开头就有结尾,玩过JSP上的EL表达式应该不会感觉很陌生吧。
搜索 </w:tr>
同样找到第二个,加上</#list>结束符。
要循环的部分如下图:
好的,这样就没问题了。