2016-06-22 20 views
0

我需要幫助將列值插入到ArrayList<String[]>結構中。如果我有這樣的Excel工作表:Apache POI將列值插入ArrayList中<String[]>

enter image description here

我用兩個數據結構。一列爲HashMap爲列名稱,ArrayList<String[]>爲值。我能夠獲得列名很好,但無法弄清楚如何獲取值。

這裏是我的代碼:

Map<String, Integer> columnNames = new HashMap<String, Integer>(); 
List<String[]> values = new ArrayList<String[]>(); 
DataFormatter dataFormat = new DataFormatter(); 
FormulaEvaluator eval = workbook.getCreationHelper().createFormulaEvaluator(); 

Row row; 
int valueIndex = 0; 

for(int i = 0; i < sheet.getLastRowNum(); i++) { 
    row = (Row) sheet.getRow(i); 

    Iterator<Cell> cells = row.cellIterator(); 

    // Read each cell in the row 
    for(int j = 0; cells.hasNext(); j++) { 
     Cell cell = cells.next(); 

     // Column Headers 
     if(cell.getRowIndex() == 0) { 
      eval.evaluate(cell); 
      String cellVal = dataFormat.formatCellValue(cell, eval); 
      columnNames.put(cellVal, j); 

     // Column values 
     } else { 
      eval.evaluate(cell); 
      String cellVal = dataFormat.formatCellValue(cell, eval); 

      // What do I write here? 
      values.add(j, //cellVal_at_valueIndex); 
     } 
    } 

    // Go to next index for values (down 1 row) 
    valueIndex++; 
} 

我不知道如何將值添加到ArrayList在這條線:

values.add(j, //cellVal_at_valueIndex); 

如果我只是把cellVal那麼就不會關聯正確地映射到HashMap的列映射。 Bascially,我希望它看起來像這樣:

HashMap:      ArrayList: 
------------------   -------------------- 
Key  | Value   String | Index   
------------------   -------------------- 
id   0    1    0 
number  1    2    1 
time   2    ...   ... 

從這裏,我可以做一些像values.get(columnNames.get("id"))[valueIndex];

我正在做這樣的,因爲可以有任意數量的每個列的和值。使用get方法從某個列中獲取值也更容易。

如何添加字符串數組中的值?我覺得我錯過了簡單的事情。提前致謝!

回答

0

嘗試類似:

if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC) 
{ 
    System.out.print(cell.getNumericCellValue()); 
    values.add(cell.getNumericCellValue()); 
} 
else if (cell.getCellType() == Cell.CELL_TYPE_STRING) 
{ 
    System.out.print(cell.getRichStringCellValue()); 
    values.add(cell.getRichStringCellValue()); 
} 
else if (cell.getCellType() == Cell.CELL_TYPE_BOOLEAN) 
{ 
    System.out.print(cell.getBooleanCellValue()); 
    values.add(cell.getBooleanCellValue()); 
} 

欲瞭解更多信息看一看Getting the cell contents鏈接。