簡體   English   中英

如何在Excel工作表的一個哈希圖中存儲第一行(標題),並在另一個哈希圖中存儲列數據

[英]How to store first row (headers) in one hash map from Excel sheet and store column data in another hashmap

Name,Branch,Collage ==> Headers in excel sheet
Sasi, CSE, JNTU-A
Sandeep, CIVIL, JNTU-H

我想要設置這樣的值,並做一些循環直到相應標題的最后一列。

("Name", "Sasi")
("Name", "Sandeep")

嘗試Apache POI。 這是一個例子:

public static void main(String[] args) {
        try { 
        FileInputStream file = new FileInputStream(new File("some_sheet.xlsx"));

        HashMap<Integer, String> headers = new HashMap<Integer, String>();
        HashMap<Object, String> cells = new HashMap<Object, String>();

        XSSFWorkbook workbook = new XSSFWorkbook(file);
        XSSFSheet sheet = workbook.getSheetAt(0);
        Iterator<Row> rowIterator = sheet.iterator();
        if (rowIterator.hasNext()) {
            Row row = rowIterator.next();
            // For each row, iterate through all the columns
            Iterator<Cell> cellIterator = row.cellIterator();
            int colNum = 0;
            while (cellIterator.hasNext()) {
                Cell cell = cellIterator.next();
                headers.put(colNum++, cell.getStringCellValue());
            }
        }
        while (rowIterator.hasNext()) {
            Row row = rowIterator.next();
            // For each row, iterate through all the columns
            Iterator<Cell> cellIterator = row.cellIterator();
            int colNum = 0;
            while (cellIterator.hasNext()) {
                Cell cell = cellIterator.next();
                cells.put(getCharValue(cell), headers.get(colNum++));
            }
        }
        file.close();

        headers.entrySet().forEach(entry->{
            System.out.println(entry.getKey() + " " + entry.getValue());
        });
        cells.entrySet().forEach(entry->{
            System.out.println(entry.getKey() + " " + entry.getValue());
        });
    } catch (Exception e) {
        e.printStackTrace();
    }
}
private static Object getCharValue(Cell cell) {
    switch (cell.getCellType()) {
        case Cell.CELL_TYPE_NUMERIC:

            return cell.getNumericCellValue();

        case Cell.CELL_TYPE_STRING:
            return cell.getStringCellValue();
    }
    return null;
}

您需要以下依賴關系:

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

根據apache poi文檔,如果單元格類型為數字,則getStringCellValue()會引發異常。

作為解決方案,您可以使用cell.getCellType()檢查類型並調用相對的getXXXCellValue()方法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM