导入freemarker依赖jar包,配置模板doc->xml->ftl,里面的数据转换成${name}这样,搞完一定要检查,以免转换错误,
public class WordExportUtil {
/**
* 配置信息,代码本身写的还是很可读的,就不过多注解了
*/
private static Configuration configuration = null;
/**
* 这里注意的是利用WordExportUtil的类加载器动态获得模板文件的位置
*/
private static final String templateFolder = WordExportUtil.class.getClassLoader().getResource("/").getPath();
/**
* @param response
* @param map 文件对象
* @param temSubFolder 模板所在resource子目录(web项目下)
* @param templateName 模板名称
* @throws IOException
*/
public static void exportWord(HttpServletResponse response, Map<String, Object> map, String temSubFolder, String templateName, String newFileName) throws IOException {
configuration = new Configuration();
configuration.setDefaultEncoding("utf-8");
//数据装配
configuration.setObjectWrapper(new DefaultObjectWrapper());
//忽略null报错
configuration.setTemplateExceptionHandler(TemplateExceptionHandler.IGNORE_HANDLER);
configuration.setDirectoryForTemplateLoading(new File(templateFolder + "/" + temSubFolder));
Template freemarkerTemplate = configuration.getTemplate(templateName + ".ftl");
PrintWriter out = null;
try {
// 调用工具类的createDoc方法生成Word文档
response.setCharacterEncoding("utf-8");
response.setContentType("application/msword");
// 设置浏览器以下载的方式处理该文件名
String fileName = newFileName + ".doc";
response.setHeader("Content-Disposition", "attachment;filename="
.concat(String.valueOf(URLEncoder.encode(fileName, "UTF-8"))));
out = response.getWriter();
freemarkerTemplate.process(map, out);
} catch (TemplateException e) {
throw new CommonExcp(EnumExcp.INTERNAL_SERVER_ERROR.getCode(), "导出失败!");
} finally {
if (out != null) {
out.close();
}
}
}
}
有问题找我,qq_1872515795