[英]How can I deal with null value in excel sheet using Java
这是我的代码段,我想以.csv的形式打印一些值来代替null。
private static void showExcelData(List sheetData) {
// LinkedHashMap<String, String> tableFields = new LinkedHashMap();
for (int i = 0; i < sheetData.size(); i++) {
List list = (List) sheetData.get(i);
for (int j = 0; j < list.size(); j++) {
Cell cell = (Cell) list.get(j);
if (cell == null || cell.getCellType() ==Cell.CELL_TYPE_BLANK) {
System.out.print("Hello_Check");
}
else if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC) {
System.out.print(cell.getNumericCellValue());
} else if (cell.getCellType() == Cell.CELL_TYPE_STRING) {
System.out.print(cell.getRichStringCellValue());
} else if (cell.getCellType() == Cell.CELL_TYPE_BOOLEAN) {
System.out.print(cell.getBooleanCellValue());
}
if (j < list.size() - 1) {
System.out.print(", ");
}
}
System.out.println("");
}
我该如何解决这个问题,以便打印一些值而不是null,因为在我的代码中,我尝试了很多步骤在excel文件中打印一些值而不是null。 谁能帮我一个忙,我怎么解决这个问题。
首先不要使用原始类型,请指定通用类型
List<List<Cell>> sheetData
List<Cell> list = sheetData.get(i);
那么util method
:
private static void print(Object o, String def){
System.out.println(o==null ? def : o.toString());
}
并使用
if (cell == null || cell.getCellType() ==Cell.CELL_TYPE_BLANK) {
print("Hello_Check");
}else if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC) {
print(cell.getNumericCellValue(), "No numeric val");
}
另外,使用foreach
和switch可以澄清代码:
for (List<Cell> list : sheetData) {
for (Cell cell : list) {
if (cell == null){
System.out.print("Hello_Check");
}else{
switch(cell.getCellType()){
case Cell.CELL_TYPE_BLANK : print("Hello_Check",""); break;
case Cell.CELL_TYPE_NUMERIC:print(cell.getNumericCellValue(),"num empty"); break;
case Cell.CELL_TYPE_STRING: print(cell.getRichStringCellValue(),"string empty"); break;
//...
}
if (j < list.size() - 1) {
System.out.print(", ");
}
}
}
System.out.println("");
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.