[英]how to read every rows in excel and save in map
我想讀取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相對應的名稱和詳細信息。因此,我嘗試使用map和key值作為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;
}
}
上面的代碼對於正常的字符串值工作正常,但是如果我在details字段中提供Json值,則映射中的值將另存為
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.