[英]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.