分组Excel中值到一个特定的行值
问题描述:
我有一个Excel工作表像分组Excel中值到一个特定的行值
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();
}
}
答
我们可以用地图来存储帐户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);
}
希望它有帮助。
这里的问题是,我不能独立读取像列标题帐户和列标题数量这两个值。 它存储在一个行对象,然后我迭代througj它是这个问题。如果你看到我如何打印这些值,以及如何知道如果该帐户的金额存在。 –
您可以检查单元格的列索引以确定您正在读取的是哪个值(例如,如果列索引为0,那么它必须是accountId,如果列索引为1,那么它必须是数量)。您可以使用'getColumnIndex()'获取列的索引。一旦读完一行的所有单元格(在遍历单元格的while循环之后),您可以将我的逻辑放置在地图内。 –
我想知道你是否可以在这里使用pojo类,我会尝试你的想法,但我们可以使用pojo –