[Java] 纯文本查看 复制代码
package com.doc;
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 MyDoc {
private Configuration configuration = null;
public MyDoc() {
configuration = new Configuration();
configuration.setDefaultEncoding("GBK");
}
public void createDoc(Map<String, Object> dataMap, String fileName,
String templateName) throws UnsupportedEncodingException {
// dataMap 要填入模本的数据文件
// 设置模本装置方法和路径,FreeMarker支持多种模板装载方法。可以重servlet,classpath,数据库装载,
// 这里我们的模板是放在com.doc.template包下面
configuration.setClassForTemplateLoading(this.getClass(),
"/com/doc/template");
Template t = null;
try {
// 要装载的模板
t = configuration.getTemplate(templateName);
} catch (IOException e) {
e.printStackTrace();
}
// 输出文档路径及名称
File outFile = new File(fileName);
Writer out = null;
FileOutputStream fos = null;
try {
fos = new FileOutputStream(outFile);
OutputStreamWriter oWriter = new OutputStreamWriter(fos, "UTF-8");
// 这个地方对流的编码不可或缺,使用main()单独调用时,应该可以,但是如果是web请求导出时导出后word文档就会打不开,并且包XML文件错误。主要是编码格式不正确,无法解析。
// out = new BufferedWriter(new OutputStreamWriter(new
// FileOutputStream(outFile)));
out = new BufferedWriter(oWriter);
} catch (FileNotFoundException e1) {
e1.printStackTrace();
}
try {
t.process(dataMap, out);
out.close();
fos.close();
} catch (TemplateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
[Java] 纯文本查看 复制代码
package com.doc;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class MyTest {
public static void main(String[] args) throws Exception {
MyTest myTest = new MyTest();
MyDoc mydoc = new MyDoc();
mydoc.createDoc(myTest.getData(), "E:/mytest.doc", "MyTest.ftl");
}
public Map<String,Object> getData(){
// title year month date no content maker validator tel
Map<String,Object> dataMap = new HashMap<String,Object>();
dataMap.put("title", "标题");
dataMap.put("year", "2016");
dataMap.put("month", "8");
dataMap.put("date", "3");
dataMap.put("maker", "柠萌小姐");
dataMap.put("validator", "Angel");
dataMap.put("tel", "010-55558888");
List<Map<String,Object>> list = new ArrayList<Map<String,Object>>();
for(int i = 1;i<=10;i++){
Map<String,Object> map = new HashMap<String,Object>();
map.put("no", i);
map.put("content", "背诵唐诗"+i+"首");
list.add(map);
}
dataMap.put("list", list);
return dataMap;
}
}