如何将从数据库中获取的值写入Excel文件

时间:2015-10-31 13:38:20

标签: java excel apache-poi

我需要你的帮助,将SQL语句中提取的值存储到excel文件中。我编写了下面的代码,但是我在如何在适当的列下编写获取的值时遇到了困难。例如,在开始时,我创建了3个标题(ID - Name - Salary)。现在,我需要在每个相应的头文件下从SQL语句中编写获取的值,但我不知道如何编写它们。亲切的帮助。代码是:

public void GenerateExcel() {
   Connection conn = null;
   Statement stmt = null;
   FileOutputStream fileOut = new FileOutputStream("C:\\Desktop\\poi-test.xls");
   HSSFWorkbook workbook = new HSSFWorkbook();
   HSSFSheet worksheet = workbook.createSheet("Employee Details");
   HSSFRow row1 = worksheet.createRow((short) 0);
   HSSFCell cellA1 = row1.createCell((short) 0);
   cellA1.setCellValue("ID");
   HSSFCell cellB1 = row1.createCell((short) 1);
   cellB1.setCellValue("Name");
   HSSFCell cellC1 = row1.createCell((short) 1);
   cellC1.setCellValue("Salary");
   try{
      Class.forName("com.mysql.jdbc.Driver");
      conn = DriverManager.getConnection(DB_URL, USER, PASS);
      stmt = conn.createStatement();

      String sql = "SELECT id, name, amount FROM Employee";
      ResultSet rs = stmt.executeQuery(sql);
      while(rs.next()){
         int id  = rs.getInt("id");
         int age = rs.getString("name");
         String first = rs.getInt("amount");
          }
      rs.close();
      workbook.write(fileOut);
      fileOut.flush();
      fileOut.close();
   }catch(SQLException se){
      se.printStackTrace();
   }catch(Exception e){
      e.printStackTrace();
   }finally{
      try{
         if(stmt!=null)
            conn.close();
      }catch(SQLException se){
      }
      try{
         if(conn!=null)
            conn.close();
      }catch(SQLException se){
         se.printStackTrace();
      }
   }
}
}

2 个答案:

答案 0 :(得分:0)

实际上我看不到你在哪里向工作簿添加数据? 我只能看到你创建工作簿并添加第一行。

while(rs.next()){
      int id  = rs.getInt("id");
      int age = rs.getString("name");
      String first = rs.getInt("amount");
      // Adding data here
      Row newRow = worksheet.createRow(worksheet.getLastRowNum() + 1);
      newRow.createCell(0).setCellValue(id);
      newRow.createCell(1).setCellValue(age);
      newRow.createCell(2).setCellValue(first);
}

答案 1 :(得分:0)

最后不要再浪费时间写Apache poi样板了。查看MemPOI的解决方案:

您可以尝试使用MemPOI。看看:

File file = new File("C:\\Desktop\\poi-test.xls")

Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(DB_URL, USER, PASS);
PreparedStatement prepStmt = this.connection.prepareStatement("SELECT id, name, amount FROM Employee");

new MempoiBuilder()
            .setFile(file)
            .addMempoiSheet(new MempoiSheet(prepStmt, "Employee Details"))
            .build()
            .prepareMempoiReportToFile()
            .get();

您可以轻松添加模板或子筛选器。看看文档