首先生成.ftl文件,也就是模板文件
1,在word里面写好自己的表格框架,或者别的样式。需要java处理填进去的数据用标红的样式标注${}中间的别名到时候与java代码中的相对应
2、将表格保存为.xml的格式,注意在这里一定要这样保存,不能通过重命名来改为.xml格式的文件
3,通过重命名的方式将.xml文件改为.ftl文件。打开为下面这样的非乱码就行了。
然后写java代码
import freemarker.template.Configuration;
import freemarker.template.Template;
import java.io.*;
import java.util.HashMap;
import java.util.Map;
public class WordGenerator {
private static Configuration configuration = null;
private static Map
allTemplates = null;
static {
configuration = new Configuration();
configuration.setDefaultEncoding("UTF-8");
configuration.setClassForTemplateLoading(WordGenerator.class, "/");//保存这个类的路径
allTemplates = new HashMap<>(); // Java 7 钻石语法
try {
//写入上面自己生成的模板文件,要注意存放的位置
allTemplates.put("SPHomeWork", configuration.getTemplate("final.ftl"));
} catch (IOException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
private WordGenerator() {
throw new AssertionError();
}
public static File createDoc(Map
dataMap, String type) {
//文件存储路径
File file =new File("D:/SocialPracticeHomeWork/"+dataMap.get("question")+"/");
//如果文件夹不存在则创建
if (!file .exists() && !file .isDirectory())
{
file .mkdir();
}
//自己创建的文件存储位置以及生成的word文件存储的名字。
String name = "D:/SocialPracticeHomeWork/"+dataMap.get("question")+"/"+dataMap.get("number") +"_" +dataMap.get("name") + ".doc";
File f = new File(name);
Template t = allTemplates.get(type);
try {
// 这个地方不能使用FileWriter因为需要指定编码类型否则生成的Word文档会因为有无法识别的编码而无法打开
Writer w = new OutputStreamWriter(new FileOutputStream(f), "utf-8");
t.process(dataMap, w);
w.close();
} catch (Exception ex) {
ex.printStackTrace();
throw new RuntimeException(ex);
}
return f;
}
}
empty
package Test;
import java.util.HashMap;
import java.util.Map;
public class WordTest {
public static void main(String[] args) {
Map
map = new HashMap
(){
private static final long serialVersionUID = 1L;
{
put("name", "name");
put("number","name");
put("class", "name");
put("answer", "< >");
put("question","name");
put("score", "name");
}
};
WordGenerator.createDoc(map, "SPHomeWork");
}
}