Java基于XML+FreeMarker导出Word

使用方法:

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;
	}
}


 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值