如何使用Java从数据库读取数据来生成Excel文件,并且该数据应该在Excel文件中分散到多个工作表中

时间:2019-02-25 06:58:22

标签: java mysql excel apache-poi

我希望在将1000行数据从数据库写入excel时,数据应自动移至下一张表。我们将如何用java编写代码(逻辑)

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)); 
             } 
             horizCount = 1 ;
             for( Employee employee: uniqueStrings ){

                 verticalCount = 0;
                 workSheet.addCell(new Label(verticalCount++,horizCount,employee.getEmployeeId(),dataFormat));`enter code here`
                 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."); 
       }

1 个答案:

答案 0 :(得分:0)

从您的代码中,我假设您是在for循环上方的某个位置创建工作表。如果写入的记录数= 1000,则在循环中创建一个新的工作表。像这样的东西

             if ((horizCount % 1000) == 0) {

                // Create a new workSheet
                workSheet = new WorkSheet();
             }