【发布时间】:2015-05-03 20:33:32
【问题描述】:
我正在尝试读取 excel 批量数据并将其保存到数据库中。在读取 excel 文件时,第一行数据被推送到 json 数组中,而在读取第二行时,它不会将数据插入到 json 中。请检查以下代码。
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":"test@gmail.com","firstname":"test","lastname":"ppppp","password":"password"},{}]
请帮我完成这个循环。
【问题讨论】:
-
您永远不会将
count重置为零,因此它永远不会在第一个字段之后向 JSON 列表添加更多字段。 -
任何解决方案。