【发布时间】:2017-07-22 04:55:19
【问题描述】:
我有一个 Excel 文件,其中的数据如下所示:
我正在使用 apache POI 库来读取 excel。因此,我使用具有多个值的单个键创建了一个 HashMap 对象:
HashMap<String, List<String>> hashMap = new HashMap<String, List<String>>();
List<String> listN = new ArrayList<String>();
现在我想通过这样的方式使用 key 来打印值:
user1 ---> [firstName, lastName, companyName, domainName, comName, emailLogin, passwordLogin, personalEmail]
user2 ---> [ccc, ccc, aaa, bbb, vvv, abc@abc.com, abc, N]
user3 ---> [sss, sss, aaa, fff, vvv, abc2@abc2.com, abc, N]
请在下面我尝试过的代码下面找到我的代码:
HashMap<String, List<String>> hashMap = new HashMap<String, List<String>>();
List<String> listN = new ArrayList<String>();
while (iterator.hasNext()) {
Row currentRow = iterator.next();
Iterator<Cell> cellIterator = currentRow.iterator();
while (cellIterator.hasNext()) {
Cell currentCell = cellIterator.next();
//getCellTypeEnum shown as deprecated for version 3.15
//getCellTypeEnum ill be renamed to getCellType starting from version 4.0
for(int j=0; j<noOfRow; j++){
for(int i=0; i<noOfColumn; i++){
if (currentCell.getRowIndex() == j && currentCell.getColumnIndex() == i) {
listN.add(currentCell.getStringCellValue());
} else if (currentCell.getCellTypeEnum() == CellType.NUMERIC) {
System.out.print(currentCell.getNumericCellValue()+ "--");
}
}
}
}
hashMap.put("user", listN);
}
for (Entry<String, List<String>> entry : hashMap.entrySet()) {
String key = entry.getKey();
Object value = entry.getValue();
System.out.println(key+" ---> "+value);
}
System.out.println();
我在循环和打印值之间卡在下面找到我的输出:
user ---> [firstName, lastName, companyName, domainName, comName, emailLogin, passwordLogin, personalEmail, ccc, ccc, aaa, bbb, vvv, abc@abc.com, abc, N, sss, sss, aaa, fff, vvv, abc2@abc2.com, abc, N]
这是我卡住的代码:
for(int j=0; j<noOfRow; j++){
for(int i=0; i<noOfColumn; i++){
if (currentCell.getRowIndex() == j && currentCell.getColumnIndex() == i) {
listN.add(currentCell.getStringCellValue());
} else if (currentCell.getCellTypeEnum() == CellType.NUMERIC) {
System.out.print(currentCell.getNumericCellValue()+ "--");
}
}
}
hashMap.put("user", listN);
我怎样才能实现相同的输出?
我们将不胜感激!
【问题讨论】:
-
您说您希望键是
user1、user2和user3,那么为什么要添加键为user的所有行? --- 你知道Map的主要特征之一是不允许重复键,对吧?所以如果你添加相同的键 3 次,只有最后一个添加停留在Map? --- 我很困惑你为什么对结果感到困惑。 -
也许
hashMap.put("user" + currentRow.getRowNum(), listN);会更好。 -
您将所有行的单元格值添加到一个
ArrayList。这应该是每行一个新的ArrayList。您将使用名为“user”的相同键将所有ArrayList放入HashMap。从您的预期结果来看,它应该是另一个键“user1”,“user2”,...每一行。但主要是你在细胞上的循环是不合逻辑的。您将Iterator用于行和单元格,然后额外的for循环也用于行和单元格。做一个或另一个。顺便说一句:noOfRow和noOfColumn来自哪里?
标签: java excel data-structures hashmap apache-poi