关于解决java读取excel文件遇空行抛空指针的问题 !
关于解决java读取excel文件遇空行抛空指针的问题 !
package exceRead; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.text.DecimalFormat; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.DateUtil; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.xssf.usermodel.XSSFCell; import org.apache.poi.xssf.usermodel.XSSFSheet; import org.apache.poi.xssf.usermodel.XSSFWorkbook; public class ExcleReadNullRow { public static void getType(XSSFCell cell) { switch (cell.getCellType()) { case Cell.CELL_TYPE_STRING: System.out.print(cell.getRichStringCellValue().getString() + "|"); // System.out.print("|"); break; case Cell.CELL_TYPE_NUMERIC: if (DateUtil.isCellDateFormatted(cell)) { System.out.print(String.valueOf(cell.getDateCellValue()) + "|"); } else { System.out.print(cell.getNumericCellValue() + "|"); } // System.out.print("|"); break; case Cell.CELL_TYPE_BOOLEAN: System.out.print(cell.getBooleanCellValue() + "|"); // System.out.print("|"); break; default: } } public static void main(String[] args) throws FileNotFoundException, IOException { ExcleUtil excle = new ExcleUtil(); String value = ""; String filePath = "C:\\Users\\ty\\Documents\\工作簿1.xlsx"; File file = new File(filePath); XSSFWorkbook wb = new XSSFWorkbook(new FileInputStream(file)); XSSFSheet sheet = wb.getSheetAt(0); int rowcount = sheet.getLastRowNum() - sheet.getFirstRowNum(); int rowcount1 = sheet.getPhysicalNumberOfRows(); System.out.println(rowcount1); System.out.println("该excle的总行数为:" + (rowcount + 1) + "行 !"); /* * int rows = sheet.getLastRowNum(); for(int i = 0; i < rows+1; i++){ // * List<String> rowData = new ArrayList<String>(); Row row = * sheet.getRow(i); if(row != null){ int cols = row.getLastCellNum(); * for(int j = 0; j < cols; j++){ XSSFCell cell = (XSSFCell) * row.getCell(j); ExcleReadNullRow.getType(cell); } // * System.out.println(); * * } */ for (int i = 0; i < rowcount + 1; i++) { Row row = sheet.getRow(i); if (row == null) { System.out.println("this row is null ----------------------"); continue; } else { for (int j = row.getFirstCellNum(); j < row.getLastCellNum(); j++) { XSSFCell cell = (XSSFCell) row.getCell(j); System.out.print("| "); if (cell != null) { ExcleReadNullRow.getType(cell); } else { continue; } } System.out.println(); } } } }
excle文件中的内容 :
java打印出出的内容 :