Quantcast
Channel: Active questions tagged excel - Stack Overflow
Viewing all articles
Browse latest Browse all 88087

How to store 2D array elements in hashmap?

$
0
0

I have a excel sheet from which i have to read all cells and store in 2D array,which i have already done.Now I want to store these 2D array elements in a hashmap. I tried using the following code but when i print the map it only prints the last read elements with its respective keys.It can be understood from the following example:-

1> My Excel sheet is:

enter image description here

2> Code to populate 2D array from excel sheet is:

String[][] excelData = new String[numRows][numCols];
            System.out.println("Populating Array....");
            for (int i=0; i<numRows; i++) 
            {
                HSSFRow row = sheet.getRow(i);
                for (int j=0; j<numCols; j++) 
                {
                    HSSFCell cell = row.getCell(j);
                    String cellValue = cellToString(cell); //cellToString is a function in class
                    excelData[i][j] = cellValue; //data stored in excelData[][] array
                }   
            }
            System.out.println("Array population complete");

3> My Code to convert 2D array into Hashmap

   System.out.println("putting in map");            
   HashMap map = new HashMap();
   for (int j = 0; j < numCols;j++) //Columns
   {                
    for (int i = 1; i < numRows;i++ ) //Rows
    {
     map.put(excelData[0][j], excelData[i][j]);
    }
   }
   System.out.println("Map values key :" +map);

4> Actual Output :-

Map values key : {Header 1=valueH1_3, Header 2=valueH2_3, Header 3=valueH3_3, Header 4=valueH4_3, Header 5=valueH5_3}

The above output is incorrect.

Expected Output:-

Map values key : {Header 1=valueH1_1,valueH1_2,valueH1_3, Header 2=valueH2_1,valueH2_2,valueH2_3, Header 3=valueH3_1,valueH3_2,valueH3_3, Header 4=valueH4_1,valueH4_2,valueH4_3, Header 5=valueH5_1,valueH5_2,valueH5_3}

Map is not able to retain previous iterated values of keys.Can anyone help please?


Viewing all articles
Browse latest Browse all 88087

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>