ApachePOI-データベース

この章では、POIライブラリがデータベースとどのように相互作用するかについて説明します。JDBCを使用すると、データベースからデータを取得し、POIライブラリを使用してそのデータをスプレッドシートに挿入できます。SQL操作用のMySQLデータベースについて考えてみましょう。

データベースからExcelに書き込む

次の従業員データテーブルを想定します。 emp_tbl MySQLデータベースから取得されます test。

EMP ID EMP名 度 給料 部門
1201 ゴパル 技術管理者 45000 それ
1202 マニシャ 校正者 45000 テスト
1203 マスタンバリ テクニカルライター 45000 それ
1204 キラン 時間管理者 40000 人事
1205 クランティ 運用管理者 30000 管理者

次のコードを使用して、データベースからデータを取得し、それをスプレッドシートに挿入します。

import java.io.File;
import java.io.FileOutputStream;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class ExcelDatabase {
   public static void main(String[] args) throws Exception {
      Class.forName("com.mysql.jdbc.Driver");
      Connection connect = DriverManager.getConnection( 
         "jdbc:mysql://localhost:3306/test" , 
         "root" , 
         "root"
      );
      
      Statement statement = connect.createStatement();
      ResultSet resultSet = statement.executeQuery("select * from emp_tbl");
      XSSFWorkbook workbook = new XSSFWorkbook(); 
      XSSFSheet spreadsheet = workbook.createSheet("employe db");
      
      XSSFRow row = spreadsheet.createRow(1);
      XSSFCell cell;
      cell = row.createCell(1);
      cell.setCellValue("EMP ID");
      cell = row.createCell(2);
      cell.setCellValue("EMP NAME");
      cell = row.createCell(3);
      cell.setCellValue("DEG");
      cell = row.createCell(4);
      cell.setCellValue("SALARY");
      cell = row.createCell(5);
      cell.setCellValue("DEPT");
      int i = 2;

      while(resultSet.next()) {
         row = spreadsheet.createRow(i);
         cell = row.createCell(1);
         cell.setCellValue(resultSet.getInt("eid"));
         cell = row.createCell(2);
         cell.setCellValue(resultSet.getString("ename"));
         cell = row.createCell(3);
         cell.setCellValue(resultSet.getString("deg"));
         cell = row.createCell(4);
         cell.setCellValue(resultSet.getString("salary"));
         cell = row.createCell(5);
         cell.setCellValue(resultSet.getString("dept"));
         i++;
      }

      FileOutputStream out = new FileOutputStream(new File("exceldatabase.xlsx"));
      workbook.write(out);
      out.close();
      System.out.println("exceldatabase.xlsx written successfully");
   }
}

上記のコードを次のように保存しましょう ExcelDatabase.java。次のようにコマンドプロンプトからコンパイルして実行します。

$javac ExcelDatabase.java
$java ExcelDatabase

名前の付いたExcelファイルを生成します exceldatabase.xlsx 現在のディレクトリで、コマンドプロンプトに次の出力を表示します。

exceldatabase.xlsx written successfully

ザ・ exceldatabase.xlsx ファイルは次のようになります。