将word 模板另存为xml格式的文件,
然后修改xml 文件
代码结构
代码如下
User类:
public class User {
private String sequence;
private String name;
private String sex;
public String getSequence() {
return sequence;
}
public void setSequence(String sequence) {
this.sequence = sequence;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
}
ExportWord类
import java.io.BufferedWriter;
import java.io.File;
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 ExportWord {
private Configuration configuration = null;
public ExportWord() {
configuration = new Configuration();
configuration.setDefaultEncoding("UTF-8");
}
// 2个参数分别是:模板的名称,导出文件的路径
public void createDoc(String modelName, String exportFilePath) {
Template t = null;
// 1、导入模板
configuration.setClassForTemplateLoading(this.getClass(), "/path");
try {
// test.ftl为要装载的模板
t = configuration.getTemplate(modelName);
} catch (IOException e) {
e.printStackTrace();
}
// 2、打包数据--每次导出的word文件模板不同,打包数据的方法要单独写
Map<String, Object> dataMap = new HashMap<String, Object>();
getData(dataMap);
// 3、导出文件
// 输出文档路径及名称
File outFile = new File(exportFilePath);
Writer out = null;
try {
out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile), "utf-8"));
} catch (Exception e1) {
e1.printStackTrace();
}
try {
t.process(dataMap, out);
} catch (TemplateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
//把数据打包成map;dataMap里存放的数据Key值要与模板中的参数相对应
private void getData(Map<String, Object> dataMap) {
//由于word中包含User,因此建立与该User属性一一对应的bean类
List<User> userList = new ArrayList<User>();
for (int i = 0; i < 10; i++) {
User user = new User();
user.setSequence(i + 1 + "");
user.setName("张三" + i+"号");
user.setSex("男" + i);
userList.add(user);
}
dataMap.put("userList", userList);
}
public static void main(String[] args) {
//复杂的列子
ExportWord dh = new ExportWord();
String filePath = "D:/克隆人名单.doc";//导出doc文件的路径
String modelName = "person.xml";//模板名称
dh.createDoc(modelName, filePath);
System.out.println(" 导出成功");
}
}
运行结果