Search code examples
javajsonexcelapache-poibufferedreader

how to read every rows in excel and save in map


I want to read every row in the excel file and save in a map.

My input file will look something like this,

ID| Name|   details
 1| xx|     {
             "user":"xx",
             "email":"[email protected]"
             }
2|  yy|     {
            "user":"yy",
            "email":"[email protected]"
             }

I want to get the values in the excel based on the provided id. if i pass the value of 2, it should return the name and details corresponding to the id - 2. so i tried to use map and key value as ID.

        String fileToParse = "D:\\InputData.xls";
    BufferedReader fileReader = null;

            String line = "";
            fileReader = new BufferedReader(new FileReader(fileToParse));    
            line = fileReader.readLine();

            Map<Long, String> dataMap = new HashMap<Long, String>();

            while ((line = fileReader.readLine()) != null)
            {      
                data dataTO = new data();
                String[] s = line.split("|");
                String value = s[1] + "," + s[2] + "," + s[3];
                dataMap.put(Long.parseLong(s[0]), value);   
            }
            long id = 2;                
            String val = dataMap.get(id);
            String url = val.split(",")[0];
            String input = val.split(",")[1];

Also my data class will have getter and setter methods for the values in excel file like this,

public class data {
private int id;

private String name;

private String details;

public int getId() {
    return id;
}

public void setId(int id) {
    this.id = id;
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public String getDetails() {
    return details;
}

public void setDetails(String details) {
    this.details = details;
}

}

The above code is working fine for normal string value but if i provide Json value in the details field, the value in map is saved as

1|Url 01|"{

instead of whole json value. Can anyone help me how to solve this problem? or is there any other approach for this?


Solution

  • A small addition to your input reading:

    String hline;
    while( (hline = fileReader.readLine()) != null){
         line = hline;
         while( ! hline.endsWith( "}" ) ){
             hline = fileReader.readLine();
             line += hline;
         }
    

    This should be put into a separate method, but I leave this to you - I don't want to change too much.