阅读 84
Springboot之导出word文件|freemarker

Springboot之导出word文件|freemarker

word模板制作

  1. word模板文件制作
  2. word转xml格式
  3. 填充数据部分可根据freemarker语法,可参照官网:freemarker.foofun.cn/

如占位符${a!''}

Controller层


public void createActivityRecord(Activity activity,HttpServletResponse response) {
        byte[] data = stglActivityService.createActivityRecord(activity);
        String name = activity.getGroupName()+".doc";
        response.reset();
        response.addHeader("Content-Disposition", "attachment; filename="+ new String(name.getBytes("GBK"), "ISO8859-1"));
        response.addHeader("Content-Length", "" + data.length);
        response.setContentType("application/octet-stream; charset=UTF-8");
        try {
          //hutool工具类
          IoUtil.write(response.getOutputStream(), Boolean.TRUE, data);
        } catch (IORuntimeException e) {
                e.printStackTrace();
        } catch (IOException e) {
                e.printStackTrace();
        }
} 
复制代码

service层


public byte[] createActivityRecord(StglActivity activity) {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        Map<String,Object> dataMap = BeanUtil.beanToMap(activity);
        WordUtils.createEvaluation(dataMap, outputStream);
        IoUtil.close(outputStream);
        return outputStream.toByteArray();
}
复制代码

utils


文件存放在src/main/resources/template
public static void createEvaluation(Map<String, Object> dataMap,ByteArrayOutputStream outputStream) {
        try {
                ClassPathResource classPathResource = new ClassPathResource("template");
                if (classPathResource.exists() && classPathResource.isFile()) {
                        configuration.setDirectoryForTemplateLoading(classPathResource.getFile());
                } else {
                        configuration.setDirectoryForTemplateLoading(new File("template"));
                }
                // 获取模板文件
                Template t = configuration.getTemplate("activity.ftl");
                StringWriter sw = new StringWriter();
                // 将填充数据填入模板文件并输出到目标文件
                t.process(dataMap, sw);
                IoUtil.write(outputStream, CharsetUtil.UTF_8, false, sw.toString());
                IoUtil.close(sw);
        } catch (TemplateException e) {
                e.printStackTrace();
        } catch (IOException e) {
                e.printStackTrace();
        }
}
复制代码
文章分类
代码人生
文章标签