我的 Excel 文件有 4 行和 2 列,例如 连续值具有 3 行第一列作为空白值,如下所示
phone plan
------------------
85366667777 PLATINUM
85367890000 GOLD
85362524232 SILVER
null SILVER
85362522436 DIAMOND
public List<List<String>> readExcelFile(String fileName) {
try {
FileInputStream fileInputStream = new FileInputStream(fileName);
POIFSFileSystem fsFileSystem = new POIFSFileSystem(fileInputStream);
HSSFWorkbook workBook = new HSSFWorkbook(fsFileSystem);
HSSFSheet hssfSheet = workBook.getSheetAt(0);
Iterator<Row> rowIterator = hssfSheet.rowIterator();
boolean headerRow = true;
while (rowIterator.hasNext()) {
if (headerRow == false) {
String Rows = util.loadfile("config/ConfigValue.properties","NoOfRowsToSkip");
int i = Integer.parseInt(Rows);
HSSFRow hssfRow = (HSSFRow) rowIterator.next();
if(hssfRow.getRowNum()==0||hssfRow.getRowNum()<=i){
continue; //just skip the rows if row number is 0 TO i
}
Iterator<Cell> iterator = hssfRow.cellIterator();
List cellTempList = new ArrayList();
while (iterator.hasNext()) {
HSSFCell hssfCell = (HSSFCell) iterator.next();
if(hssfCell.getCellType() == hssfCell.CELL_TYPE_NUMERIC)
{DecimalFormat df = new DecimalFormat("#");
String cellValue=df.format(hssfCell.getNumericCellValue());
cellTempList.add(cellValue.toString());
}
else if(hssfCell.getCellType() == hssfCell.CELL_TYPE_STRING)
{
cellTempList.add(hssfCell.toString());
}
}
cellDataList.add(cellTempList);
} else {
headerRow = false;
}
}
} catch (Exception e) {
e.printStackTrace();
logger.error("Other Exception : " + e.getStackTrace());
}
System.out.println(cellDataList);
return cellDataList;
}
}
输出:[[85366667777,白金],[85367890000,黄金],[85362524232,白银],[白银],[85362522436,钻石]]
当对应的单元格中没有值时,为什么不打印[null,Silver]
或[0,SILVER]
?
最佳答案
if(hssfCell.getCellType() == hssfCell.CELL_TYPE_NUMERIC){
DecimalFormat df = new DecimalFormat("#");
String cellValue=df.format(hssfCell.getNumericCellValue());
cellTempList.add(cellValue.toString());
} else if(hssfCell.getCellType() == hssfCell.CELL_TYPE_STRING){
cellTempList.add(hssfCell.toString());
} else {
cellTempList.add(null); // or cellTempList.add("0");
}
您的空单元格既不是字符串也不是数字,因此没有任何内容添加到您的数组中。尝试检查 CELL_TYPE_BLANK。
关于java - 读取Excel的空白单元格并返回List<List<String>>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21044455/