在使用freemarker向word中导入数据时,有两个基础的步骤,如下

1、创建Word模板,保存为.xml格式

2、将要替换的内容,以${}装载

学生信息 姓名 ${name}
性别 ${gender}
学科 ${subject}
成绩 ${score}

 

 (1)、加载ftl模板

 (2)、替换内容

 (3)、输出文本

 首先写一个通用的导出Word的一个类:

 

package com.test.freemarker;

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.UnsupportedEncodingException;
import java.io.Writer;
import java.util.Map;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;

public class DocumentHandler {
private Configuration con=null;

public DocumentHandler(){

con = new Configuration();
con.setDefaultEncoding("utf-8");
}

public void createDoc(Map<String,Object> dataMap,String fileName) throws UnsupportedEncodingException{

//设置模板装置方法和路径
//模板放在temp包下
con.setClassForTemplateLoading(this.getClass(),"/template1");
Template t=null;

//为 test.ftl装载模板
try {
t=con.getTemplate("test.ftl");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

//输出文档路径及名称
File outFile=new File(fileName);
Writer out =null;
FileOutputStream fos=null;

try {

fos=new FileOutputStream(outFile);
OutputStreamWriter osw=new OutputStreamWriter(fos,"UTF-8");//这个地方对流的编码不可或缺
out =new BufferedWriter(osw);

} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}

try {

//输出文本
t.process(dataMap, out);
out.close();
fos.close();

} catch (TemplateException | IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

 然后通过调用上面类的方法,将数据导出到Word中:

public static void main(String[] args) throws UnsupportedEncodingException {
// TODO Auto-generated method stub
Map<String, Object> dataMap = new HashMap<String, Object>();

dataMap.put("name1", "编写员1");
dataMap.put("name2", "编写员2");
dataMap.put("name3", "编写员3");
dataMap.put("name4", "编写员4");
dataMap.put("name5", "编写员5");

//导出word
DocumentHandler doc = new DocumentHandler();
doc.createDoc(dataMap, "E:/基础管理任务分配.doc");

}

最后会在E盘下创建一个名为基础管理任务分配的Word文档。

posted on 2015-05-30 17:50  程序媛Kasey  阅读(406)  评论(0)    收藏  举报