簡體   English   中英

將數據從 Excel 文件存儲到 Java 集合

[英]Storing data to Java Collection from Excel file

我想從 Excel 文件中讀取數據,並希望將 HashMap 之類的東西存儲到 Java 集合中。

我已經通過 Apache POI 實現了 Excel 讀取——這部分工作得很好。 現在我想知道如何將該數據存儲到 HashMap 中。

我創建了 1 個具有 Excel 數據值的 POJO 類。

Class EmpXcel
    private String emp_name;
    private String emp_job;

     // parameterised constructor

     // getter-setter

現在,如果我創建此特定 POJO 類的類型的 HashMap。

例如。 Map<String, EmpXcel> map = new HashMap<String, EmpXcel>();

這是我從 Excel 讀取數據的代碼。

while(itr.hasNext()){
            Row nextRow = itr.next();
            // For each row, iterate through all the columns
            Iterator<Cell> cellIterator = nextRow.cellIterator();

            while (cellIterator.hasNext()) 
            {
                Cell cell = cellIterator.next();

                switch (cell.getCellType()) 
                {
                    //  if cell is numeric format   
                    case Cell.CELL_TYPE_NUMERIC:
                        System.out.print(cell.getNumericCellValue()+",");
                        break;

                    // if cell is string format
                    case Cell.CELL_TYPE_STRING:
                        System.out.print(cell.getStringCellValue() + ",");
                        break;
                }
            } 
         System.out.println();
    }

我不確定如何將此數據存儲到 POJO 類(此處為 EmpXcel)類型的 HashMap 中。

編輯:Excel表格:

Emp_Name |  Emp_Job

Travis   |  Technical Assistant

John     |  Professor

另外我想讓它更通用 - 想要為不同的 Excel 文件創建單個 Java 類(不管行/列的數量)

請與我分享您的一些見解,以便我可以遵循這種方式。

謝謝。

回答您的最后一條評論@inityk 通過使用 getColumnIndex(),您可以訪問所有單元格,然后可以驗證其中的數據。

List<EmpXcel> empXcelList=new Arrayist<EmpXcel>();
   while(itr.hasNext()){
        Row nextRow = itr.next();
        EmpXcel empXcelPOJO = new EmpXcel();
        // For each row, iterate through all the columns
        Iterator<Cell> cellIterator = nextRow.cellIterator();

        while (cellIterator.hasNext()) 
        {
            Cell cell = cellIterator.next();

            if(cell.getColumnIndex()==0) 
            {
                case Cell.CELL_TYPE_NUMERIC:
                    System.out.print("Name should not be numeric");
                    break;

                // if cell is string format
                case Cell.CELL_TYPE_STRING:
                    empXcelPOJO.setEmpName(cell.getStringCellValue())
                    break;
            }elseif(cell.getColumnIndex()==1) 
            {
                case Cell.CELL_TYPE_NUMERIC:
                    System.out.print("Name should not be numeric");
                    break;

                // if cell is string format
                case Cell.CELL_TYPE_STRING:
                    empXcelPOJO.setEmpJob(cell.getStringCellValue())
                    break;
            }
        } 
     empXcelList.add(empXcelPOJO);
    }

暫無
暫無

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

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