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

How to write fetched values from database to Excel file

我需要你的帮助,以便将 SQL 语句中获取的值存储到 excel 文件中。我写了下面的代码,但我在如何在适当的列下写入获取的值方面遇到了困难。比如一开始我创建了3个headers(ID - Name - Salary)。现在,我需要在每个适当的header下写下从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();
      }
   }
}
}

实际上我看不到您在工作簿中添加数据的位置? 我只能看到你创建了工作簿并添加了第一行。

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);
}

终于不再浪费时间编写 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();

您可以轻松添加模板或子标题。看看文档