我正在尝试使用 Apache poi jar 从 Excel 工作表中获取数据。我的 Excel 中有三行四列。实际数据在第二行和第三行。第一行是标题,我将其用作获取值的键。当我这样做时,我得到的输出总是显示第三行数据。我尝试对其进行调试并观察到第二行数据被第三行覆盖。
这是我的代码片段
public static void main(String[] args) throws IOException {
loadExcel();
Map<String, Map<String, String>> superMap = new HashMap<String, Map<String,String>>();
Map<String, String> hm = new HashMap<>();
for (int i = 1; i < excelSheet.getLastRowNum() + 1; i++) {
int lastColnum = excelSheet.getRow(0).getLastCellNum();
for (int j = 0; j < lastColnum; j++) {
System.out.println("reading excel column");
String key = excelSheet.getRow(0).getCell(j).getStringCellValue();
String value = excelSheet.getRow(i).getCell(j).getStringCellValue();
hm.put(key, value);
}
superMap.put("MASTERDATA", hm);
}
for (Entry<String, Map<String, String>> set : superMap.entrySet()) {
System.out.println(set.getKey() + " : " + set.getValue());
}
}
输出:
MASTERDATA : {Blood Group=test2bg, UserName=test2, Address=test2add, Password=test2pass}
我的 Excel 数据:
Username | Password | Address | Blood Group
test1 | test1pass |test1add | test1bg
test2 | test2passs|test2add | test2bg
我尝试过将 map 放入 superMap 中,但仍然没有成功。任何建议/建议都会有所帮助。提前致谢。
最佳答案
问题出在这一行,您为每一行放置相同的 key
superMap.put("MASTERDATA", hm);
您可以使用行号,即外循环的 i
var 来使其可变且唯一
编辑
Map<String, Map<String, String>> superMap = new HashMap<String, Map<String,String>>();
for (int i = 1; i < excelSheet.getLastRowNum() + 1; i++) {
Map<String, String> hm = new HashMap<>();
int lastColnum = excelSheet.getRow(0).getLastCellNum();
for (int j = 0; j < lastColnum; j++) {
System.out.println("reading excel column");
String key = excelSheet.getRow(0).getCell(j).getStringCellValue();
String value = excelSheet.getRow(i).getCell(j).getStringCellValue();
hm.put(key, value);
}
superMap.put("MASTERDATA_" + i, hm);
}
得到类似的东西
MASTERDATA_1 : {Blood Group=test1bg, UserName=test1, Address=test1add, Password=test1pass}
MASTERDATA_2 : {Blood Group=test2bg, UserName=test2, Address=test2add, Password=test2pass}
关于java - 迭代 Map 时,Map 值被覆盖,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62740031/