我试图在Java中使用Apache进行excel读写操作。当我试图传递excel中没有任何数据的单元格时,它将返回空白,但是- Java指针异常将抛出instead.However,而当我传递具有某些数据的单元格时,getCelldata和setCelldata都工作得很好。下面是代码片段
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
public class ExcelUtils {
private static XSSFSheet ExcelWSheet;
private static XSSFWorkbook ExcelWBook;
private static XSSFCell xCell;
private static XSSFRow xRow;
//This method is to set the File path and to open the Excel file, Pass Excel Path and Sheetname as Arguments to this method
public static void setExcelFile(String Path,String SheetName) throws Exception {
try {
// Access the required test data sheet
FileInputStream inputStream = new FileInputStream(new File(Path));
ExcelWBook = new XSSFWorkbook(inputStream);
ExcelWSheet = ExcelWBook.getSheet(SheetName);
} catch (Exception e){
throw (e);
}
}
//This method is to read the test data from the Excel cell, in this we are passing parameters as Row num and Col num
public static String getCellData(int RowNum, int ColNum) throws Exception{
try{
xCell = ExcelWSheet.getRow(RowNum).getCell(ColNum, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK);
String CellData = xCell.getStringCellValue();
return CellData;
}catch (Exception e){
throw(e);
}
}
//This method is to write in the Excel cell, Row num and Col num are the parameters
public static void setCellData(String Result, int RowNum, int ColNum) throws Exception {
try{
xRow = ExcelWSheet.getRow(RowNum);
xCell = xRow.getCell(ColNum, Row.MissingCellPolicy.RETURN_BLANK_AS_NULL);
if (xCell == null) {
xCell = xRow.createCell(ColNum);
xCell.setCellValue(Result);
} else {
xCell.setCellValue(Result);
}
// Constant variables Test Data path and Test Data file name
FileOutputStream fileOut = new FileOutputStream(Constants.Path_TestData);
ExcelWBook.write(fileOut);
fileOut.flush();
fileOut.close();
}catch(Exception e){
throw (e);
}
}
}
在行时抛出错误但预期的xCell应该有空值,因为我提供了MissingCellPolicy
xCell = ExcelWSheet.getRow(RowNum).getCell(ColNum, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK);
和
xCell = xRow.getCell(ColNum, Row.MissingCellPolicy.RETURN_BLANK_AS_NULL);
提前谢谢
发布于 2018-04-23 19:31:21
可能您正在传递一个完全为空的行,这就是getRow()方法失败的原因,并为您提供了一个NullPointerException。
当您在一行中的列上迭代时,一些空白的单元甚至可能不存在,这可能会导致不知情的代码抛出一个NullPointerException。MissingCellPolicy只应用于单元格。所以你不能让整行空着
CREATE_NULL_AS_BLANK --如果返回的单元格不存在,则创建一个单元格类型为“空白”的新单元格,而不是返回null。这样可以方便地避免NullPointerExceptions。
RETURN_BLANK_AS_NULL --即使单元格存在但单元格类型为“空白”,也返回null。这可以让您忽略空白区,这些单元格确实很容易存在。
RETURN_NULL_AND_BLANK --不要修改现有的结构;对于不存在的单元格返回null,如果空单元格存在,则返回空单元格,但其单元格类型是空的。这是不需要getCell的MissingCellPolicy过载的行为。
https://stackoverflow.com/questions/49988587
复制相似问题