excel-Spreadsheets:讀取Excel電子表格資料的Java原始碼

banq發表於2020-06-07

這是一個使用Apacahe POI和Java以程式設計方式從excel電子表格中讀取資料的原始碼專案,點選標題進入。

Maven配置:

<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi</artifactId>
    <version>4.1.2</version>
</dependency>
 
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-ooxml</artifactId>
    <version>4.1.2</version>
</dependency>


1. 開啟電子表格

File file = new File("resources/Test Data.xlsx");

try(var workbooks = WorkbookFactory.create(file)){

}catch(Exception e){
    e.printStackTrace();
}


2.切換到工作表

try(var workbooks = WorkbookFactory.create(spreadsheet)){
    currentSheet = workbooks.getSheet("john");
}catch(Exception e){
    e.printStackTrace();
}


3.讀取標題行

Map<String, Integer> columns;
Sheet currentSheet;

try(var workbooks = WorkbookFactory.create(spreadsheet)){
    currentSheet = workbooks.getSheet("john");
    currentSheet.getRow(0).forEach(cell ->{
        columns.put(cell.getStringCellValue(), cell.getColumnIndex());
    });
}catch(Exception e){
    e.printStackTrace();
}


4.從單元獲取資料

int row = 1;
String accountId = getCellData("Account ID", row);
String transactionId = getCellData("Transaction ID", row);

public String getCellData(String column, int row){
    var dataRow = currentSheet.getRow(row);
    return getCellDataAsString(dataRow.getCell(columns.get(column)));
}

public String getCellDataAsString(Cell cell){
    return  switch(cell.getCellType()){
        case STRING -> cell.getStringCellValue();
        case NUMERIC -> String.valueOf((int)cell.getNumericCellValue());
        default -> "";
    };
}

 

相關文章