如何在Excel中读取每一行并保存在地图中



我想读取 excel 文件中的每一行并保存在地图中。

我的输入文件看起来像这样,

ID| Name|   details
 1| xx|     {
             "user":"xx",
             "email":"xxx@xxx.in"
             }
2|  yy|     {
            "user":"yy",
            "email":"yyy@xxx.in"
             }

我想根据提供的 id 获取 excel 中的值。 如果我传递值 2,它应该返回与 id - 2 对应的名称和详细信息。所以我尝试使用地图和键值作为 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];

此外,我的数据类将具有 excel 文件中值的 getter 和 setter 方法,如下所示,

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;
}

}

上面的代码对于普通字符串值工作正常,但是如果我在详细信息字段中提供 Json 值,则 map 中的值将另存为

1|Url 01|"{

而不是整个 JSON 值。谁能帮我解决这个问题?还是有其他方法?

对输入读数的一个小补充:

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

这应该放在一个单独的方法中,但我把它留给你 - 我不想改变太多。

我强烈建议使用像Apache POI这样的库来读取excel文件。您可以在此处找到有关读取和写入文件的详细信息:http://poi.apache.org/spreadsheet/quick-guide.html#ReadWriteWorkbook

优点是您不必尝试了解 xls 文件的格式。

如果您使用的是任何依赖项管理生成系统,则可以简单地将依赖项添加到项目中,或者将 jar 文件直接添加到项目中。http://mvnrepository.com/artifact/org.apache.poi/poi/3.11

最新更新