Apache POIでExcelのファイルを読み込む
以下のExcelファイルを読み込みます。
# | name | point |
---|---|---|
1 | ベッテル | 397 |
2 | アロンソ | 242 |
3 | ウェバー | 199 |
POIを使ったコードはこんな感じ。
import java.io.FileInputStream; import java.io.InputStream; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.ss.usermodel.WorkbookFactory; public class PoiTest { public static void main(String[] args) throws Exception { // excelファイルのオープン InputStream inputStream = new FileInputStream("excel/f1_2013.xlsx"); Workbook workbook = WorkbookFactory.create(inputStream); // シートの取得 Sheet sheet = workbook.getSheet("drivers"); // 行読み込み(1行目は見出し行なので、2行目以降のデータを読んでいる) for (int i = 1; i < Integer.MAX_VALUE; i++) { Row row = sheet.getRow(i); if (row == null) { break; } // セルの取得 Cell num = row.getCell(0); Cell name = row.getCell(1); Cell point= row.getCell(2); // データの表示 System.out.printf("%.0f\t%s\t%.0f\n", num.getNumericCellValue(), name.getStringCellValue(), point.getNumericCellValue()); } } }
実行結果
1 ベッテル 397 2 アロンソ 242 3 ウェバー 199