hutool-动态导出表头导出


准备

  官方网站:https://www.hutool.cn/docs/#/

  public static void writeExcel(HttpServletResponse response, ExcelWriter writer, String fileName) {
        //response为HttpServletResponse对象
        response.setContentType("application/vnd.ms-excel;charset=utf-8");
        //test.xls是弹出下载对话框的文件名,不能为中文,中文请自行编码
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
        ServletOutputStream servletOutputStream = null;
        try {
            servletOutputStream = response.getOutputStream();
            //Workbook workbook = writer.getWorkbook();
            // workbook.write(servletOutputStream);
            writer.flush(servletOutputStream);
            servletOutputStream.flush();
        } catch (IORuntimeException | IOException e) {
            e.printStackTrace();
        } finally {
            writer.close();
            try {
                if (servletOutputStream != null) {
                    servletOutputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
工具类

 

步骤1 

    /**
     * 表头
     *
     * @param writer 导出文件
     * @param titleName 表头参数
     */
    private void header(ExcelWriter writer, List<String> titleName) {
        int headerCol = -1;
        for (String typeName : titleName) {
            ExcelHelper.mergeIfNeed(writer, 0, 0, ++headerCol, headerCol + 2, 20, typeName);
            writer.writeCellValue(headerCol, 1, "序号");
            writer.writeCellValue(++headerCol, 1, "名称");
            writer.writeCellValue(++headerCol, 1, "联系人");
        }
    }
表头

步骤2

  表格之间计算  row   col   i 根据自己的需求调整

 

/**
     * 导出数据
     *
     * @param writer 文件
     * @param mainList 数据
     * @param titleName 表头
     */
    private void body(ExcelWriter writer, List<SourcePatrolMain> mainList, List<String> titleName) {
        int row = 1;
        int col = 0;
        int i = 0;
        for (String title : titleName) {
            i++;
            int nub = 1; 
            //这里筛选数据每个表头数据
            for (SourcePatrolMain main : 筛选数据) {
                col = 3 * i == 3 ? 0 : 3 * (i - 1);
                row++;
                writer.writeCellValue(col++, row, nub++);
                writer.writeCellValue(col++, row, main.getMianName());
                writer.writeCellValue(col++, row,main.getManager()+" "+ main.getPhone());
            }
            row = 1;
        }
    }         
导出数据

 

 

 

步骤3

/*
 * titleList 表头
 * mainList 导出数据
 */
ExcelWriter writer = ExcelUtil.getWriter();
header(writer, titleList);
body(writer, mainList, titleList);
ExcelHelper.writeExcel(response, writer, "fileName.xls");

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM