当使用Apache POI处理Excel文件时抛出了NullPointerException(NPE)异常,可能是由于以下几种原因引起的:
文件路径错误:请确保文件路径是正确的,包括文件名、文件类型和文件位置。
文件格式错误:请确保正在处理的文件是Excel文件,并且使用了正确的Apache POI库版本。不同的Excel文件格式需要使用不同的POI库版本。
下面是一个示例代码,演示了如何使用Apache POI处理Excel文件:
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.FileInputStream;
import java.io.IOException;
public class ApachePOIExample {
public static void main(String[] args) {
String filePath = "path/to/your/excel/file.xlsx";
try {
FileInputStream fis = new FileInputStream(filePath);
Workbook workbook = new XSSFWorkbook(fis);
Sheet sheet = workbook.getSheetAt(0);
for (Row row : sheet) {
for (Cell cell : row) {
// 处理单元格数据
CellType cellType = cell.getCellType();
if (cellType == CellType.STRING) {
String cellValue = cell.getStringCellValue();
System.out.println(cellValue);
} else if (cellType == CellType.NUMERIC) {
double cellValue = cell.getNumericCellValue();
System.out.println(cellValue);
}
}
}
workbook.close();
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
请确保将path/to/your/excel/file.xlsx
替换为实际的Excel文件路径。如果仍然出现NullPointerException异常,请检查文件路径和格式是否正确,以及是否正确导入了Apache POI库。