Java html转word,用freemark生成复杂word格式
程序员文章站
2024-01-14 19:29:22
...
1.**制作模板**,要求word版本2003以上。在word写好预定的格式,在需要显示内容的地方写一个占位符。将word
save as 成“Single File Web Page(*.mht, *mhtml)”
nodepad++ 打开mht文件,将占位符加上${name},并将文件中的charset设置为utf-8,有时候需要将格式转换utf-8不然中文会出现乱码.
demo: http://download.csdn.net/detail/rehuojunguan/9857489
2.freemark class 主要读取模板 template,根据map的中数据替换mht文件中的 ${key},最后生成word。
public class FreeMarkerDoc {
private String templateName = null;
private String templatePath = null;
private Configuration configuration = null;
public FreeMarkerDoc() {
configuration = new Configuration(Configuration.VERSION_2_3_21);
configuration.setDefaultEncoding("utf-8");
}
public void generateDoc(Map<String,Object> dataMap, String fileName) throws IOException, TemplateException {
Template tempalte = null;
configuration.setClassForTemplateLoading(this.getClass(), "/com/freemark/template");
//setServletContextForTemplateLoading(context, "/mht") /WebRoot/ftl目录。
//configuration.setDirectoryForTemplateLoading(new File("C:\\Users\\Desktop\\test"));
///tempalte.setEncoding("utf-8");
tempalte = configuration.getTemplate("test.mht");
File outFile = new File(fileName);
Writer out = null;
FileOutputStream fos = null;
OutputStreamWriter oWriter = null;
try {
fos = new FileOutputStream(outFile);
oWriter = new OutputStreamWriter(fos, "UTF-8");
out = new BufferedWriter(oWriter);
tempalte.process(dataMap, out);
} finally {
if(null != out){
out.close();
}
if(null != oWriter){
oWriter.close();
}
if(null != fos){
fos.close();
}
}
}
}