如何使用Java将数据库中的数据打印到Excel到多张工作表中,每张工作表的范围为40000行

时间:2019-02-27 07:17:19

标签: java excel jexcelapi

我正在尝试使用Java将数据从数据库打印到excel工作表,但是由于数据数量很大,我遇到了“线程java.lang.OutOfMemoryError:Java堆空间异常”。我希望在40000行之后数据应打印在下一张纸上。

public class ExcelSheetGenerator {

    public static String generateExcelSheetReport(List<Employee> employeeList, String filePath, String fileName)
            throws Exception {

        Set<Employee> uniqueStrings = new HashSet<Employee>();
        uniqueStrings.addAll(employeeList);
        // create WorkbookSettings object
        WorkbookSettings ws = new WorkbookSettings();
        WritableWorkbook workbook = null;
        // Workbook workbook = new HSSFWorkbook();
        try {
            // File file = new File("D:\\tmpFolder\\Production\\StoreVisitDailyReport.xls");
            File file = new File(filePath + fileName);
            System.out.println("FIle is::::::" + file + ":::::" + filePath + "::::" + fileName);
            System.out.println("FIle is::::::" + file + ":::::" + filePath + "::::" + fileName);
            // create work sheet

            workbook = Workbook.createWorkbook(file, ws);

            WritableSheet workSheet;
            workSheet = workbook.createSheet("Employee", 0);
            SheetSettings sh = workSheet.getSettings();
            // workSheet.setName("StoreVisitReport");

            // Creating Writable font to be used in the report
            WritableFont headerFont = new WritableFont(WritableFont.createFont("Arial"),
                    WritableFont.DEFAULT_POINT_SIZE, WritableFont.BOLD, false, UnderlineStyle.NO_UNDERLINE);

            WritableFont normalFont = new WritableFont(WritableFont.createFont("Arial"),
                    WritableFont.DEFAULT_POINT_SIZE, WritableFont.BOLD, false, UnderlineStyle.NO_UNDERLINE);
            // creating plain format to write data in excel sheet

            WritableCellFormat headerFormat = new WritableCellFormat(headerFont);

            headerFormat.setBackground(Colour.GRAY_50);

            headerFormat.setShrinkToFit(true);
            headerFormat.setWrap(true);
            headerFormat.setAlignment(jxl.format.Alignment.CENTRE);
            headerFormat.setVerticalAlignment(VerticalAlignment.CENTRE);
            headerFormat.setBorder(jxl.format.Border.ALL, jxl.format.BorderLineStyle.THIN, jxl.format.Colour.BLACK);

            WritableCellFormat dataFormat = new WritableCellFormat(normalFont);

            dataFormat.setAlignment(jxl.format.Alignment.CENTRE);
            dataFormat.setVerticalAlignment(VerticalAlignment.CENTRE);
            dataFormat.setWrap(true);
            dataFormat.setBorder(jxl.format.Border.ALL, jxl.format.BorderLineStyle.THIN, jxl.format.Colour.BLACK);

            List<String> header = new ArrayList<String>();
            header.add("EmployeeId");
            header.add("EmployeeEmailId");
            header.add("EmployeeAddress");
            header.add("EmployeePhonenumber");
            header.add("EmployeePincode");

            int horizCount = 0;
            int verticalCount = 0;
            for (String head : header) {
                workSheet.addCell(new Label(verticalCount++, horizCount, head, headerFormat));
                // HSSFWorkbook workbook1 = new HSSFWorkbook();
            }
            horizCount = 1;

            for (Employee employee : uniqueStrings) {

                if (horizCount % 40000 == 0) {
                    workSheet = workbook.createSheet("Employee", 1);
                }

                verticalCount = 0;
                workSheet.addCell(new Label(verticalCount++, horizCount, employee.getEmployeeId(), dataFormat));
                workSheet.addCell(new Label(verticalCount++, horizCount, employee.getEmployeeEmailId(), dataFormat));
                workSheet.addCell(new Label(verticalCount++, horizCount, employee.getEmployeeadddress(), dataFormat));
                workSheet.addCell(new Label(verticalCount++, horizCount, employee.getEmployeephoneno(), dataFormat));
                workSheet.addCell(new Label(verticalCount++, horizCount, employee.getEmployeepincode(), dataFormat));
                horizCount++;

            }
            // write to the excel sheet
            workbook.write();

            // close the workbook
            workbook.close();
        } catch (FileNotFoundException e) {
            // workbook.write();

            // close the workbook
            workbook.close();
            throw new IOException("File Not found exception occured.");
        } catch (IOException e) {
            // workbook.write();

            // close the workbook
            workbook.close();
            throw new IOException(e.getMessage());
        } catch (Exception e) {
            // workbook.write();

            // close the workbook
            workbook.close();

            throw new Exception(e.getMessage());
        }
        System.out.println("<======Inside generateExcelSheetReport=====end");
        System.out.println("<======Inside generateExcelSheetReport=====end");
        return "success";
    }

    private static void workSheet() {
        // TODO Auto-generated method stub

    }
}

1 个答案:

答案 0 :(得分:0)

如果使用CSV,在文本文件中使用更好的制表符分隔值将是可行的,那么那将是最好的:您可以按顺序将其写出,这是最快的。 (缺点:.xlsx可能无法压缩。)

将数据库与顺序查询一起使用,uniqueStrings不必要。

增加应用程序java -Xmx2g的内存。

.xslx是zip格式,可能最适合。但是也尝试.xls,它通常更快,可能会让我们感到惊讶。

请尝试使用SXSSFWorkbook,因为此流版本不应将整个DOM,对象模型保留在内存中

  

实现“ BigGridDemo”策略的XSSFWorkbook的流版本。这允许写入非常大的文件而不会用完内存,因为任何时候只有一行的可配置部分都保留在内存中。

我会保留最简单的方法,而不是深刻地模仿Excel。

  • Workbook.createSheet
  • Sheet.createRow
  • Row.createCell
  • Cell.setCellValue

丢弃new LabeldataFormat