2013-11-20 50 views
0

我必須創建一個計算GPA的程序,使用讀取xlsx excel文件的apache poi。它印有220行4列,如將Excel列轉換爲Java使用API​​

Course Number Course Name Credit Hours Course Multipler 
110    Eng 1 CP  5.0   1.0 

還有220個其他課程。 但是,我能夠使用cell.getStringCellValue和cell.getNumericCellValue來打印這些數據,但我無法將這些打印數據存入每個數組中。

我想創造稱爲courseNumList陣列並把courseNumList [0]的第一道菜號和在courseNumList第二療程數[1] ..上和..

我想創建4個陣列,但什麼是好方法?

  private static ArrayList<Object> c = new ArrayList <Object>(); 

      public static void readXLSXFile() throws IOException { 

    InputStream ExcelFileToRead = new FileInputStream("C:/Users/14KimTa/Desktop/Downloads/Course_List.xlsx"); 

    XSSFWorkbook wb = new XSSFWorkbook(ExcelFileToRead); 

    XSSFWorkbook test = new XSSFWorkbook(); 

    XSSFSheet sheet = wb.getSheetAt(0); 
    XSSFRow row; 
    XSSFCell cell; 

    Iterator rows = sheet.rowIterator(); 

    while (rows.hasNext()) 
    { 
     row=(XSSFRow) rows.next(); 
     Iterator cells = row.cellIterator(); 

     while (cells.hasNext()) 
     { 
      cell=(XSSFCell) cells.next(); 

      if (cell.getCellType() == XSSFCell.CELL_TYPE_STRING) 
      {    
       System.out.print(cell.getStringCellValue()+" "); 
            c.add(getStringCellValue()); 
      } 

      else if(cell.getCellType() == XSSFCell.CELL_TYPE_NUMERIC) 
      { 
       System.out.print(cell.getNumericCellValue()+" "); 
      } 
     }   

    System.out.println(); 
    } 

} 

這是我的代碼到目前爲止。

我試圖創建每個列到數組中,但它根本不工作。

謝謝!

回答

0

我不認爲每列創建一個數組是個好主意。通過遵循4個陣列中的相同索引來跟蹤同一行中的數據可能是麻煩且不好的做法。

我寧願創建一個Java類 - Course - 與4場 - courseNumbercourseNamecreditHourscourseMultiplier。然後,我會創建一個這樣的對象集合,例如Collection<Course> courses = new ArrayList<Course>();,並根據從Excel讀取的數據填充它 - 每行一個對象。

編輯:

我建議你創建一個自定義類型,而不是使用ObjectArrayList類型參數。通過使用Object你並沒有太大的收穫。

然後,對於每一行,你會做到以下幾點:

//...obtain your values from cells and populate `courseNumber`, `courseName`,`creditHours` and `courseMultiplier` accordingly 
Course course = new Course(); 
course.setCourseNumber(courseNumber); 
course.setCourseName(courseName); 
course.setCreditHours(creditHours); 
course.setCourseMultiplier(courseMultiplier); 
c.add(course); 

此代碼段應放在您使用通過迭代行內循環。

+0

我無法將每個行放一個對象 – user2760357

+0

請發佈您迄今爲止編碼的內容。 –

+0

如何「獲取」這些值?我應該使用添加功能嗎? – user2760357

2

我會創建一個新類來定義您的數據Course,每個列(4個字段)有一個字段。然後我會創建一些ListArrayList<Course>看起來不錯),以容納所有CoursesCourse也可以工作,因爲你知道一開始有多少。在一個循環中,我將爲每一行創建一個Course對象,根據cell.getStringCellValue()cell.getNumericCellValue()中的值設置字段,在處理每一行後將Course添加到List(或數組)。

+0

我試圖這樣做,但它出錯了。 – user2760357

+0

每行不會像我打算進入一個數組,但所有的數據只是簡單地進入arrayList [0] ..如果我嘗試arrayList [1],它會返回一個錯誤 – user2760357

+0

請顯示您的代碼,創建您的代碼對象並將它們插入到你的'ArrayList'中。 – rgettman