JAVA生成Word文档(经过测试)

首先告诉大家这篇文章的原始出处:http://www.havenliu.com/java/514.html/comment-page-1#comment-756

 

我也是根据他所描述完成的,但是有一些地方有点模糊,不容易弄出来.所以,我另外写一篇,让大家少走一些弯路.

 

 

上图:是Word文档中的内容,也就是模板,为了下面步鄹做铺垫,所以在需要输入数据的地方改成了拼音,

 

将word文档另存为xml文件.

 

 

接下来,上面写的拼音就起到作用了.

打开xml文件.搜索 title.

将Title 改为 ${title}

其他地方一样的修改。

改完后,把文件的后缀名直接改成ftl。

 

然后呢,直接上代码:

 

package com;

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 {
	
	private Configuration configuration = null;
	
	public WordTest(){
		configuration = new Configuration();
		configuration.setDefaultEncoding("UTF-8");
	}
	
	public static void main(String[] args) {
		WordTest test = new WordTest();
		test.createWord();
	}
	
	public void createWord(){
		Map<String,Object> dataMap=new HashMap<String,Object>();
		getData(dataMap);
		configuration.setClassForTemplateLoading(this.getClass(), "/com");  //FTL文件所存在的位置
		Template t=null;
		try {
			t = configuration.getTemplate("wordModel.ftl"); //文件名
		} catch (IOException e) {
			e.printStackTrace();
		}
		File outFile = new File("O:/outFilessa"+Math.random()*10000+".doc");
		Writer out = null;
		try {
//			out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile)));
              out = new OutputStreamWriter(new FileOutputStream(f), "utf-8");//使用上面的会因为编码问题造成文档无法打开 } 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("title", "标题"); dataMap.put("year", "2012"); dataMap.put("month", "2"); dataMap.put("day", "13"); dataMap.put("auditor", "唐鑫"); dataMap.put("phone", "13020265912"); dataMap.put("weave", "占文涛"); // dataMap.put("number", 1); // dataMap.put("content", "内容"+2); List<Map<String,Object>> list = new ArrayList<Map<String,Object>>(); for (int i = 0; i < 10; i++) { Map<String,Object> map = new HashMap<String,Object>(); map.put("number", i); map.put("content", "内容"+i); list.add(map); } dataMap.put("list", list); } }


大家现在可能最关心的是遍历的文件。接下来我们看如何遍历数据。

 

 

 
在刚刚的那个ftl文件中直接编辑:
打开FTL文件,搜索   <w:tr
找到第一个,tr的意思不用解释了吧,代表着一行。
这也意味着我找到了Table中的第一行,但是我需要遍历的不是从第一行开始,而是从第二行。
好的,继续搜索,找到第二个。
 
 
在它的头上加一个<#list 你的集合名称 as xxxx>
ok,有开头就有结尾,玩过JSP上的EL表达式应该不会感觉很陌生吧。
搜索 </w:tr>
同样找到第二个,加上</#list>结束符。
好的,这样就没问题了。
posted @ 2015-11-27 15:55  晨羲  阅读(480)  评论(0编辑  收藏  举报