本章说明POI库如何与数据库交互。借助JDBC,您可以使用POI库从数据库中检索数据并将其插入电子表格中。让我们考虑将MySQL数据库用于SQL操作。

从数据库写入Excel

让我们假设要从MySQL数据库test中检索以下名为emp_tbl的员工数据表。

EMP ID EMP NAME DEG SALARY DEPT
1201 Gopal Technical Manager 45000 IT
1202 Manisha Proof reader 45000 Testing
1203 Masthanvali Technical Writer 45000 IT
1204 Kiran Hr Admin 40000 HR
1205 Kranthi Op Admin 30000 Admin

使用以下代码从数据库检索数据,并将其插入电子表格中。

  1. import java.io.File;
  2. import java.io.FileOutputStream;
  3.  
  4. import java.sql.Connection;
  5. import java.sql.DriverManager;
  6. import java.sql.ResultSet;
  7. import java.sql.Statement;
  8.  
  9. import org.apache.poi.xssf.usermodel.XSSFCell;
  10. import org.apache.poi.xssf.usermodel.XSSFRow;
  11. import org.apache.poi.xssf.usermodel.XSSFSheet;
  12. import org.apache.poi.xssf.usermodel.XSSFWorkbook;
  13.  
  14. public class ExcelDatabase {
  15. public static void main(String[] args) throws Exception {
  16. Class.forName("com.mysql.jdbc.Driver");
  17. Connection connect = DriverManager.getConnection(
  18. "jdbc:mysql://localhost:3306/test" ,
  19. "root" ,
  20. "root"
  21. );
  22.  
  23. Statement statement = connect.createStatement();
  24. ResultSet resultSet = statement.executeQuery("select * from emp_tbl");
  25. XSSFWorkbook workbook = new XSSFWorkbook();
  26. XSSFSheet spreadsheet = workbook.createSheet("employe db");
  27.  
  28. XSSFRow row = spreadsheet.createRow(1);
  29. XSSFCell cell;
  30. cell = row.createCell(1);
  31. cell.setCellValue("EMP ID");
  32. cell = row.createCell(2);
  33. cell.setCellValue("EMP NAME");
  34. cell = row.createCell(3);
  35. cell.setCellValue("DEG");
  36. cell = row.createCell(4);
  37. cell.setCellValue("SALARY");
  38. cell = row.createCell(5);
  39. cell.setCellValue("DEPT");
  40. int i = 2;
  41.  
  42. while(resultSet.next()) {
  43. row = spreadsheet.createRow(i);
  44. cell = row.createCell(1);
  45. cell.setCellValue(resultSet.getInt("eid"));
  46. cell = row.createCell(2);
  47. cell.setCellValue(resultSet.getString("ename"));
  48. cell = row.createCell(3);
  49. cell.setCellValue(resultSet.getString("deg"));
  50. cell = row.createCell(4);
  51. cell.setCellValue(resultSet.getString("salary"));
  52. cell = row.createCell(5);
  53. cell.setCellValue(resultSet.getString("dept"));
  54. i++;
  55. }
  56.  
  57. FileOutputStream out = new FileOutputStream(new File("exceldatabase.xlsx"));
  58. workbook.write(out);
  59. out.close();
  60. System.out.println("exceldatabase.xlsx written successfully");
  61. }
  62. }

让我们将上面的代码另存为ExcelDatabase.java。如下从命令提示符编译并执行它。

  1. $javac ExcelDatabase.java
  2. $java ExcelDatabase

它将在当前目录中生成一个名为exceldatabase.xlsx的Excel文件,并在命令提示符下显示以下输出。

  1. exceldatabase.xlsx written successfully

该exceldatabase.xlsx文件如下所示。

exceldatabase.jpeg