2016-03-02 37 views
0

我有一個Excel工作表像分組Excel中值到一個特定的行值

enter image description here

I want output values as 
1 - 10 
2 - 23 
3 - 13 
4 - 29 

使用集合,我知道我必須收藏的Hashmap但我能弄清楚。

到目前爲止我的代碼

public class Test { 

public static void main(String[] args) throws IOException { 
    String excelFilePath = "C:\\Users\\SINGH\\Desktop\\test.xlsx"; 
    FileInputStream inputStream = new FileInputStream(new File(excelFilePath)); 

    Workbook workbook = new XSSFWorkbook(inputStream); 
    Sheet firstSheet = workbook.getSheetAt(0); 
    Iterator<Row> iterator = firstSheet.iterator(); 
    ArrayList<Integer> amount = new ArrayList<Integer>(); 
    Map<Integer, ArrayList<Integer>> map = new HashMap<Integer,ArrayList<Integer>>(); 

    while (iterator.hasNext()) { 
     Row nextRow = iterator.next(); 
     Iterator<Cell> cellIterator = nextRow.cellIterator(); 

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

      switch (cell.getCellType()) { 
      case Cell.CELL_TYPE_STRING: 
       //System.out.print(cell.getStringCellValue()); 
       break; 
      case Cell.CELL_TYPE_NUMERIC: 
       System.out.print(cell.getNumericCellValue()); 
       amount.add((int) cell.getNumericCellValue()); 

      } 


      System.out.print(" - "); 
     } 
     System.out.println(); 
    } 
    System.out.println(); 
    workbook.close(); 
    inputStream.close(); 
} 

} 

回答

0

我們可以用地圖來存儲帳戶ID和相應的金額。而且,當通過Excel工作表迭代時,如果某個值已經存在,那麼我們可以將現有值添加到該表中並再次存儲。下面是示例代碼:

Map<Integer, Integer> accounts = new LinkedHashMap<Integer, Integer>(); 
int accountId = //read account id from excel 
int amount = //read amount from excel 
//If entry already exists in map then, add the new value to existing value 
if(accounts.containsKey(accountId)){ 
    amount += accounts.get(accountId); 
} 
//set the value in map, this will replace the existing value 
accounts.put(accountId, amount); 

*更新*作爲詢問意見,使用POJO的 替代的解決方案,我們可以創建類似下面的一個DTO類:

class AccountDto{ 
    private int accountId; 
    private int amount; 

    //getters and setters 
} 

然後,我們可以使用列表來存儲Dto對象。我們還需要方法來檢查dto是否已經存在於列表中(使用accountId),如果是,那麼我們可以只添加數量。以下是pseido代碼:

List<AccountDto> accounts = new ArrayList<AccountDto>(); 
int accountId = //read account id from excel 
int amount = //read amount from excel 

AccountDto accountDto = findById(accountId, accounts); 
//Check whether account exists in the list 
if(null == accountDto){ 
    //If not then add a new object 
    accountDto = new AccountDto(accountId, amount); 
}else{ 
    //If yes then, add the amount 
    accountDto.setAmount(accountDto.getAmount() + amount); 
} 

希望它有幫助。

+0

這裏的問題是,我不能獨立讀取像列標題帳戶和列標題數量這兩個值。 它存儲在一個行對象,然後我迭代througj它是這個問題。如果你看到我如何打印這些值,以及如何知道如果該帳戶的金額存在。 –

+0

您可以檢查單元格的列索引以確定您正在讀取的是哪個值(例如,如果列索引爲0,那麼它必須是accountId,如果列索引爲1,那麼它必須是數量)。您可以使用'getColumnIndex()'獲取列的索引。一旦讀完一行的所有單元格(在遍歷單元格的while循環之後),您可以將我的邏輯放置在地圖內。 –

+0

我想知道你是否可以在這裏使用pojo類,我會嘗試你的想法,但我們可以使用pojo –

相關問題