java word文档导出统计功能

  1. 上代码
@GetMapping("/word")
    public void generateWord(HttpServletResponse response) throws IOException, XDocReportException, FileNotFoundException {
        //获取Word模板,模板存放路径在项目的resources目录下
        InputStream ins = this.getClass().getResourceAsStream("/templates/operatingStatistics.docx");
        //注册xdocreport实例并加载FreeMarker模板引擎
        IXDocReport report = XDocReportRegistry.getRegistry().loadReport(ins,
            TemplateEngineKind.Freemarker);
        //创建xdocreport上下文对象
        IContext context = report.createContext();

        //创建要替换的文本变量
        context.put("unitName", "恩施州保障中心");

        List<UnitStatistics> goodsList = new ArrayList<UnitStatistics>();
        UnitStatistics goods1 = new UnitStatistics();
        goods1.setInitiatorUnitCodeName("单位111");
        goods1.setDateCount(11);
        goods1.setMileages(675512L);
        goods1.setFrequency("589");
        UnitStatistics goods2 = new UnitStatistics();
        goods1.setInitiatorUnitCodeName("单位222");
        goods1.setDateCount(12);
        goods1.setMileages(675512L);
        goods1.setFrequency("9");
        UnitStatistics goods3 = new UnitStatistics();
        goods1.setInitiatorUnitCodeName("单位333");
        goods1.setDateCount(13);
        goods1.setMileages(76312L);
        goods1.setFrequency("12");
        UnitStatistics goods4 = new UnitStatistics();
        goods1.setInitiatorUnitCodeName("单位444");
        goods1.setDateCount(14);
        goods1.setMileages(679812L);
        goods1.setFrequency("36");
        goodsList.add(goods1);
        goodsList.add(goods2);
        goodsList.add(goods3);
        goodsList.add(goods4);
        context.put("goods", goodsList);

        //创建字段元数据
        FieldsMetadata fm = report.createFieldsMetadata();
        //Word模板中的表格数据对应的集合类型
        fm.load("goods", UnitStatistics.class, true);

        //输出到本地目录
//        FileOutputStream out = new FileOutputStream(new File("D://运行统计表demo.docx"));
//        report.process(context, out);
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/msword");
        String fileName = "统计分析报表.docx";
        response.setHeader("Content-Disposition", "attachment;filename="
            .concat(String.valueOf(URLEncoder.encode(fileName, "UTF-8"))));
        report.process(context, response.getOutputStream());
    }
  1. 看模板
    java word文档导出统计功能
上一篇:Flutter状态管理终极方案GetX第一篇——路由(1),Android程序员必会


下一篇:开发十年老架构师:Android性能优化实践,程序员如何应对中年危机