将Excel值分组到特定的行值

时间:2016-03-02 17:49:44

标签: java apache-poi

我有一张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();
}

}

1 个答案:

答案 0 :(得分: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);

* update * 正如评论中所述,使用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);
}

希望它有所帮助。

相关问题