根据模板导出word的util

导入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

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值