
本文详解解决java+selenium+apache poi读取excel时因文件扩展名判断错误导致的nullpointerexception问题,并提供健壮、可复用的excel数据读取实现方案。
在使用Apache POI进行数据驱动自动化测试时,一个常见但极易被忽视的错误是文件扩展名比对不严谨——如原代码中 fileExtension.equals("xls") 缺少前导点号,导致 loginWorkbook 初始化失败,进而引发 NullPointerException(Cannot invoke "Workbook.getSheet()" because "loginWorkbook" is null)。
? 根本原因分析
fileName.substring(fileName.indexOf(".")) 返回的是类似 ".xlsx" 或 ".xls" 的字符串(含点号),而原代码却用 "xls"(无点号)进行比对,条件永远为 false,loginWorkbook 保持 null,后续调用 getSheet() 必然崩溃。
✅ 正确写法应为:
里面有2个文件夹。其中这个文件名是:finishing,是我项目还没有请求后台的数据的模拟写法。请求后台数据之后,瀑布流的js有一点点变化,放在文件名是:finished。变化在于需要穿参数到后台,和填充的内容都用后台的数据填充。看自己项目需求来。由于chrome模拟器是不允许读取本地文件json的,所以如果你要进行测试,在hbuilder打开项目就可以看到效果啦,或者是火狐浏览器。
if (fileExtension.equalsIgnoreCase(".xlsx")) {
loginWorkbook = new XSSFWorkbook(fis);
} else if (fileExtension.equalsIgnoreCase(".xls")) {
loginWorkbook = new HSSFWorkbook(fis);
} else {
throw new IllegalArgumentException("Unsupported file extension: " + fileExtension);
}✅ 完整修复版代码(含关键优化)
package com.framework;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.time.Duration;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class DataDriveFramework {
public void readExcel(String filePath, String fileName, String sheetName) throws IOException {
File file = new File(filePath + File.separator + fileName); // 使用File.separator提升跨平台兼容性
if (!file.exists()) {
throw new IOException("Excel file not found: " + file.getAbsolutePath());
}
FileInputStream fis = new FileInputStream(file);
Workbook workbook = null;
String fileExtension = fileName.substring(fileName.lastIndexOf("."));
try {
if (fileExtension.equalsIgnoreCase(".xlsx")) {
workbook = new XSSFWorkbook(fis);
} else if (fileExtension.equalsIgnoreCase(".xls")) {
workbook = new HSSFWorkbook(fis);
} else {
throw new IllegalArgumentException("Unsupported Excel format: " + fileExtension);
}
} finally {
fis.close(); // 避免资源泄漏(建议后续改用try-with-resources)
}
Sheet sheet = workbook.getSheet(sheetName);
if (sheet == null) {
throw new IllegalArgumentException("Sheet not found: " + sheetName);
}
int firstRow = sheet.getFirstRowNum();
int lastRow = sheet.getLastRowNum();
// 从第1行开始(跳过表头),确保行存在且非空
for (int i = firstRow + 1; i <= lastRow; i++) {
Row row = sheet.getRow(i);
if (row == null) continue; // 跳过空行
Cell usernameCell = row.getCell(0);
Cell passwordCell = row.getCell(1); // ⚠️ 原代码误用getCell(0)两次!已修正为索引1
String username = getCellValue(usernameCell);
String password = getCellValue(passwordCell);
if (username != null && !username.trim().isEmpty()) {
test(username, password);
}
}
workbook.close(); // 显式关闭Workbook释放资源
}
// 安全获取单元格值(兼容String/numeric/boolean类型)
private String getCellValue(Cell cell) {
if (cell == null) return "";
switch (cell.getCellType()) {
case STRING:
return cell.getStringCellValue().trim();
case NUMERIC:
if (DateUtil.isCellDateFormatted(cell)) {
return cell.getDateCellValue().toString();
} else {
return String.valueOf((long) cell.getNumericCellValue()).trim();
}
case BOOLEAN:
return String.valueOf(cell.getBooleanCellValue()).trim();
default:
return "";
}
}
public void test(String username, String password) {
WebDriver driver = new FirefoxDriver();
try {
driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(10));
driver.get("https://accounts.google.com");
driver.findElement(By.id("identifierId")).sendKeys(username);
driver.findElement(By.xpath("//span[text()='Next']")).click(); // 更稳定的定位方式
// 注意:实际项目中需显式等待密码框出现,此处仅为示例
driver.findElement(By.name("Passwd")).sendKeys(password); // 替换为更鲁棒的定位器
driver.findElement(By.xpath("//span[text()='Next']")).click();
} finally {
driver.quit(); // 确保每次执行后释放浏览器实例
}
}
public static void main(String[] args) throws IOException {
DataDriveFramework framework = new DataDriveFramework();
String filePath = "C:\\Users\\Shefali\\eclipse-workspace\\DataDriveFramework\\TestExcelSheet\\";
framework.readExcel(filePath, "DataDriven.xls", "Sheet1");
}
}⚠️ 关键注意事项与最佳实践
- 扩展名校验必须带点号:.xls ≠ xls,推荐使用 equalsIgnoreCase() 提升容错性;
- 索引修正:原代码 getCell(0) 被重复用于用户名和密码,应分别对应列0(用户名)和列1(密码);
- 空行/空单元格防护:添加 row == null 和 cell == null 判空,避免 NullPointerException;
- 资源管理:务必 close() FileInputStream 和 Workbook,推荐升级为 try-with-resources;
- 定位器稳定性:避免硬编码XPath(如 /html/body/div[1]/...),优先使用 By.name()、By.cssSelector() 或显式等待;
- 异常处理增强:对文件不存在、Sheet不存在、不支持格式等场景主动抛出明确异常,便于调试。
通过以上修复与优化,你的数据驱动框架将具备更强的健壮性、可维护性和跨环境适应能力。










