2015-05-03 72 views
0

我正在嘗試讀取excel批量數據並將其保存到數據庫中。當讀取excel文件的第一行數據被推入到json數組中時,在讀取第二行時它不會將數據插入到json中。請檢查下面的代碼。如何將第二個對象添加到jsonArray中

private JsonArray readBulkUsers(String file) throws IOException { 
int count = 0; 
FileInputStream fis = new FileInputStream(file); 
//Get the workbook instance for XLS file 
    HSSFWorkbook workbook = new HSSFWorkbook(fis); 
    //Get first sheet from the workbook 
    HSSFSheet sheet = workbook.getSheetAt(0); 

    JsonArrayBuilder blist = Json.createArrayBuilder(); 

    //Iterate through each rows from first sheet 
    Iterator<Row> rowIterator = sheet.iterator(); 
    JsonObjectBuilder userjson = Json.createObjectBuilder(); 
    while(rowIterator.hasNext()) { 
     Row row = rowIterator.next(); 

     if(row.getRowNum()==0){ 
      continue; //just skip the rows if row number is 0 
     } 

     Iterator<Cell> cellIterator = row.cellIterator(); 
     while(cellIterator.hasNext()) {     
      Cell cell = cellIterator.next(); 
      if(count == 0) { 
      userjson.add("email", cell.getStringCellValue()); 
      } else if(count == 1) { 
       userjson.add("firstname", cell.getStringCellValue()); 
      } else if(count == 2) { 
       userjson.add("lastname", cell.getStringCellValue()); 
      } else if(count == 3) { 
       userjson.add("password", cell.getStringCellValue()); 
      } 
      count ++; 

     } 

    blist.add(userjson.build()); 
} 
    fis.close(); 
    return blist.build(); 
} 

低於價值我得到: [{ 「電子郵件」: 「[email protected]」, 「名字」: 「測試」, 「姓氏」: 「PPPPP」, 「密碼」:「密碼「},{}]

請幫我完成這個循環。

+0

你永遠不會重置'count'回零裏面創建一個新的JsonObjectBuilder,所以它絕不會後第一個到JSON列表中添加多個字段。 –

+0

任何解決方案。 – user3222441

回答

0

的同時

while(rowIterator.hasNext()) 
    { 
    count=0; 
    Row row = rowIterator.next(); 

    if(row.getRowNum()==0){ 
     continue; //just skip the rows if row number is 0 
    } 
    JsonObjectBuilder userjson = Json.createObjectBuilder(); 
    Iterator<Cell> cellIterator = row.cellIterator(); 
    while(cellIterator.hasNext()) {     
     Cell cell = cellIterator.next(); 
     if(count == 0) { 
     userjson.add("email", cell.getStringCellValue()); 
     } else if(count == 1) { 
      userjson.add("firstname", cell.getStringCellValue()); 
     } else if(count == 2) { 
      userjson.add("lastname", cell.getStringCellValue()); 
     } else if(count == 3) { 
      userjson.add("password", cell.getStringCellValue()); 
     } 
     count ++; 

    } 

blist.add(userjson.build()); 

}

+0

感謝您的幫助。它現在有效 – user3222441

相關問題