我想读取 Excel 文件中的每一行并保存在 map 中。
我的输入文件看起来像这样,
ID| Name| details
1| xx| {
"user":"xx",
"email":"xxx@xxx.in"
}
2| yy| {
"user":"yy",
"email":"yyy@xxx.in"
}
我想根据提供的id获取excel中的值。如果我传递值 2,它应该返回与 id - 2 对应的名称和详细信息。 所以我尝试使用 map 和键值作为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;
}
这应该放入一个单独的方法中,但我把它留给你 - 我不想改变太多。
关于java - 如何读取Excel中的每一行并保存在 map 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27729156/