JAVA POI导出Execl表格生成多个sheet的实现

接上一篇文章链接:SpringBoot集成POI导出Execl表格之统一工具类。补中了一个Execl表格根据数量生成多个sheet(比如我们有10万条数据导出Execl表格,且不说会不会内存溢出问题,一个表格存这个多数据要下拉框也要拉很长时间)

解决:我们可以在一个Execl表格中创建多个sheet分别来存放这些数据,这样就解决了一些问题,也方便查看。

效果如下:

JAVA POI导出Execl表格生成多个sheet的实现_第1张图片

具体的jar包依赖等,在里就不细说了,可以看上一篇文章:SpringBoot集成POI导出Execl表格之统一工具类

代码:

    //每个sheet最多导出多少条数据
    public static final int SHEET_COUNT = 3;


    /**
     * 写excel. 拆分多个sheet
     * xls方式
     * @param response 响应流
     * @param fileName 文件名称
     * @param titleColumn 对应bean的属性名
     * @param titleName   excel要导出的列名
     * @param titleSize   列宽
     * @param dataList    数据
     */
    public static void writeExcel(HttpServletResponse response, String fileName, String titleColumn[], String titleName[], int titleSize[], List dataList) {
        //添加Worksheet(不添加sheet时生成的xls文件打开时会报错)
        HSSFWorkbook workbook = new HSSFWorkbook();

        OutputStream out = null;
        try{
            //新建文件
            out = response.getOutputStream();
            String lastFileName = fileName + ".xls";
            response.setContentType("application/msexcel;charset=UTF-8");
            response.setHeader("Content-Disposition", "attachment; filename="
                    + URLEncoder.encode(lastFileName, "UTF-8"));
            int k = 0;
            int rowIndex;
            Sheet sheet = workbook.createSheet(fileName + (k + 1));
            //写入excel的表头
            Row titleNameRow = workbook.getSheet(fileName + (k + 1)).createRow(0);
            //设置样式
            CellStyle titleStyle = workbook.createCellStyle();
            for (int i = 0; i < titleName.length; i++) {
                sheet.setColumnWidth(i, titleSize[i] * 256);    //设置宽度
                Cell cell = titleNameRow.createCell(i);
                cell.setCellStyle(titleStyle);
                cell.setCellValue(titleName[i]);
            }

            //通过反射获取数据并写入到excel中
            if (dataList != null && dataList.size() > 0) {
                if (titleColumn.length > 0) {
                    for (int index = 0; index < dataList.size(); index++) {
                        //设置多个sheet
                        //每个sheet3W条数据
                        if (index != 0 && (index) % SHEET_COUNT == 0) {
                            k = k + 1;
                            sheet = workbook.createSheet(fileName + (k + 1));
                            //写入excel的表头
                            titleNameRow = workbook.getSheet(fileName + (k + 1)).createRow(0);
                            for (int i = 0; i < titleName.length; i++) {
                                sheet.setColumnWidth(i, titleSize[i] * 256);    //设置宽度
                                Cell cell = titleNameRow.createCell(i);
                                cell.setCellStyle(titleStyle);
                                cell.setCellValue(titleName[i]);
                            }
                        }
                        if (index < SHEET_COUNT) {
                            rowIndex = index + 1;
                        } else {
                            rowIndex = index - SHEET_COUNT * ((index) / SHEET_COUNT) + 1;
                        }

                        Object obj = dataList.get(index);     //获得该对象
                        Class clsss = obj.getClass();     //获得该对对象的class实例
                        Row dataRow = workbook.getSheet(fileName + (k + 1)).createRow(rowIndex);
                        for (int columnIndex = 0; columnIndex < titleColumn.length; columnIndex++) {
                            String title = titleColumn[columnIndex].toString().trim();
                            if (!"".equals(title)) {  //字段不为空
                                //使首字母大写
                                String UTitle = Character.toUpperCase(title.charAt(0)) + title.substring(1, title.length()); // 使其首字母大写;
                                String methodName = "get" + UTitle;

                                // 设置要执行的方法
                                Method method = clsss.getDeclaredMethod(methodName);

                                //获取返回类型
                                String returnType = method.getReturnType().getName();
                                Object object = method.invoke(obj);
                                String data = method.invoke(obj) == null ? "" : object.toString();
                                Cell cell = dataRow.createCell(columnIndex);
                                if (data != null && !"".equals(data)) {
                                    if ("int".equals(returnType)) {
                                        cell.setCellValue(Integer.parseInt(data));
                                    } else if (Date.class.getName().equals(returnType)) {
                                        cell.setCellValue(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(object));
                                    } else {
                                        cell.setCellValue(data);
                                    }
                                }
                            }
                        }
                    }
                }
            }
            workbook.write(out);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (out != null) {
                try {
                    out.flush();
                    out.close();
                } catch (IOException e) {
                    logger.debug("导出写Excel异常");
                }
            }
        }
    }

 

测试:

    @RequestMapping("/export")
    public void export(HttpServletResponse response) {
        List dataList = new ArrayList<>();
        User user1 = new User("张三", 23, "男", 173);
        User user2 = new User("李四", 20, "男", 183);
        User user3 = new User("王五", 25, "男", 165);
        User user4 = new User("小花", 18, "女", 165);
        dataList.add(user1);
        dataList.add(user2);
        dataList.add(user3);
        dataList.add(user4);
        //多次填充测试数据
        dataList.add(user1);
        dataList.add(user2);
        dataList.add(user3);
        dataList.add(user4);
        dataList.add(user1);
        dataList.add(user2);
        dataList.add(user3);
        dataList.add(user4);

        try {


            //导出xsl格式(拆分多个sheet)
            ExcelExportUtil.writeExcel(response, "用户信息导出数据",new String[]{"name", "age", "sex", "height"}
                    , new String[]{"姓名", "年龄", "性别", "身高"}
                    , new int[]{30, 30, 30, 30}, dataList);
        } catch (Exception e) {
            e.printStackTrace();
        }
    } 
  

 

上一篇中也有拆分多个sheet的代码,但导出格式为(SXSSFWorkbook)xlsx的格式,本篇说明的是(HSSFWorkbook)xls的格式。

你可能感兴趣的:(工具类)