2015-10-31 52 views
-1

我需要您的帮助来将从SQL语句中提取的值存储到Excel文件中。我写了下面的代码,但是我在如何在合适的列下写入提取的值时遇到困难。例如,在开始时,我创建了3个标题(ID - Name - Salary)。现在,我需要在每个适当的头文件中写入SQL语句中的提取值,但我不知道如何编写它们。所以善意协助。代码是:如何将从数据库提取的值写入Excel文件

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(); 
     } 
    } 
} 
} 
+0

*我面临困难* - 哪个/哪里? – pnuts

+0

阅读此http://examples.javacodegeeks.com/core-java/writeread-excel-files-in-java-example/ –

+0

http://stackoverflow.com/questions/19655813/how-to-write-data- in-multiple-cells-in-excel-using-java –

回答

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

我会尝试上述解决方案 – 99maas

相关问题