プログラミング逆引き辞典

~ 多言語対応のプログラミングレシピ ~

SpringBoot Excelファイル読み込み

POIを使ってエクセルファイルを読み込む方法
 
 

■依存関係にPOIを追加

//2003年以前のExcel(xls)
implementation 'org.apache.po:poi:4.1.2'
//2007年移行のExcel(xlsx)
implementation 'org.apache.poi:poi-ooxml:4.1.2'

 
 


■コントローラークラス

package com.example.controller;

import java.io.File;
import java.io.IOException;

import org.apache.poi.EncryptedDocumentException;
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;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class MainController {
    @GetMapping
    String index() throws EncryptedDocumentException, IOException {
        //読み込み対象のExcelのファイルパス
        String filePath = "C:/LoadFile/sample.xlsx";

        //読み込んだExcelのインスタンスを作成
        Workbook workbook = WorkbookFactory.create(new File(filePath));

        //シートを指定
        Sheet sheet = workbook.getSheet("Sheet1");

        //行を指定 ※1行目
        Row row = sheet.getRow(0);

        //列を指定 ※1列目
        Cell cell = row.getCell(0);

        //指定したセルに入力されている値を取得
        String result = cell.getStringCellValue();

        return result;
    }
}

 
 

■【参考】関数処理

//サーバ側でPOIに再計算させる
workbook.getCreationHelper().createFormulaEvaluator().evaluateAll();

//クライアント側でExcelアクセス時に再計算
sheet.setForceFormulaRecalculation(true);