java - 迭代 Map 时,Map 值被覆盖

标签 java excel apache-poi

我正在尝试使用 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/

相关文章:

java - 如何将旧文件从 Java Eclipse 工作区复制到新工作区?

java - 用Future实现缓存过期

excel - VBA 不匹配 IF 语句

excel - 一起使用 IF AND OR ..?

java - Apache POI 是否支持 Excel 函数 CUBEMEMBER?

java - Selenide 找不到 Web 元素

java - 无法为扩展名“application”设置未知属性 'mainClass'

java - 将图像插入 Excel - Java

apache-poi - 从java中的模板文件创建docx文件

java - Apache POI - 缓存工作簿是重用的最佳方式吗?