您的位置:首页 > 编程语言 > Java开发

Java基于XML+FreeMarker导出Word

2013-03-28 14:09 627 查看
使用方法:

1、先用word制作模版,参数使用freemarker的写法 ${xxx} 暂时只支持这一种

2、然后将word另存为xml

3、再将xml拷贝一份,后缀名改为ftl

4、freemarker解析ftl输出word

public class WordExportAction extends AbstractAction {

private Configuration configuration = null;
private Template template = null;// 模版

private void init(String filename, String templatePath) throws Exception {

response.setContentType("application/msword;charset=UTF-8");
response.setHeader("Content-Disposition", "inline;filename="
+ java.net.URLEncoder.encode(filename, "UTF-8"));
// 客户端不缓存
response.addHeader("Pargam", "no-cache");
response.addHeader("Cache-Control", "no-cache");

configuration = new Configuration();

configuration.setDefaultEncoding("utf-8");

String templateName = templatePath.substring(templatePath
.lastIndexOf("\\"));

String templateRoot = templatePath.substring(0, templatePath
.lastIndexOf("\\"));

// 设置模本装置方法和路径,FreeMarker支持多种模板装载方法。可以重servlet,classpath,数据库装载,
configuration.setDirectoryForTemplateLoading(new File(templateRoot));

template = configuration.getTemplate(templateName);

template.setEncoding("utf-8");

// 指定模板如何检索数据模型,这是一个高级的主题了…
// 但先可以这么来用:
configuration.setObjectWrapper(new DefaultObjectWrapper());
}

/**
* 导出word
* @param filename 导出的文件名
* @param dataMap 参数集合
* @param templatePath 模版路径
* @throws Exception
*/
public void export(String filename, Map dataMap, String templatePath)
throws Exception {

// 初始化
init(filename, templatePath);

//执行导出
template.process(dataMap, response.getWriter());
}

}


测试action

public class ExportWordTestAction extends WordExportAction{

public String doExport() throws Exception{
Map dataMap = new HashMap();
// 在根中放入字符串"user"
dataMap.put("dept", "研发部");
dataMap.put("code", "r$d");
dataMap.put("date", "2013-3-3");
dataMap.put("addr", "天府软件园");

String templatePath = "jsp/demosys/reports/word/test.ftl";

export("03月27日常州03-⊥-C50停电申请单.doc",dataMap,templatePath);
return null;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: