excel-Spreadsheets:读取Excel电子表格数据的Java源码

20-06-07 banq

这是一个使用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 -> "";
    };
}

 

    

猜你喜欢