本文详解修复 apache poi 读取 excel 时因文件扩展名判断错误导致的 `nullpointerexception`,并提供健壮、可复用的数据驱动测试代码,涵盖 `.xls`/`.xlsx` 兼容处理、空单元格防护、资源释放及最佳实践。
在使用 Apache POI 实现 Selenium 数据驱动自动化测试时,一个常见却极易被忽视的错误是文件扩展名字符串匹配不准确,这将直接导致 Workbook 对象初始化失败,进而引发 NullPointerException ——正如您遇到的错误:
java.lang.NullPointerException: Cannot invoke "org.apache.poi.ss.usermodel.Workbook.getSheet(String)" because "loginWorkbook" is "null"
根本原因在于 readExcel() 方法中对 .xls 扩展名的判断逻辑存在硬编码缺陷:
else if(fileExtension.equals("xls")) // ❌ 错误:缺少前导点号由于 fileName.substring(fileName.indexOf(".")) 返回的是类似 ".xls" 或 ".xlsx" 的完整扩展名(含英文句点),而代码中却错误地与 "xls"(无点)比较,导致条件始终为 false,loginWorkbook 保持 null,后续调用 getSheet() 必然崩溃。
✅ 正确写法应为:
else if (fileExtension.equalsIgnoreCase(".xls"))同时,为提升健壮性与可维护性,我们建议对原始代码进行以下关键优化:
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 file
Path, 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 = null;
Workbook workbook = null;
try {
fis = new FileInputStream(file);
String fileExtension = fileName.substring(fileName.lastIndexOf(".")).toLowerCase();
if (fileExtension.equals(".xlsx")) {
workbook = new XSSFWorkbook(fis);
} else if (fileExtension.equals(".xls")) {
workbook = new HSSFWorkbook(fis);
} else {
throw new IllegalArgumentException("Unsupported file format: " + fileExtension);
}
Sheet sheet = workbook.getSheet(sheetName);
if (sheet == null) {
throw new IllegalArgumentException("Sheet not found: " + sheetName);
}
int firstRowNum = sheet.getFirstRowNum();
int lastRowNum = sheet.getLastRowNum();
// 从第1行开始(跳过表头),确保行存在且非空
for (int i = firstRowNum + 1; i <= lastRowNum; i++) {
Row row = sheet.getRow(i);
if (row == null) continue; // 跳过空行
// 安全读取单元格:处理 null、blank 和不同数据类型
String username = getCellStringValue(row.getCell(0));
String password = getCellStringValue(row.getCell(1)); // ⚠️ 注意:原代码误用 getCell(0) 两次!
if (username != null && !username.trim().isEmpty() &&
password != null && !password.trim().isEmpty()) {
test(username, password);
}
}
} finally {
// 确保资源释放
if (fis != null) fis.close();
if (workbook != null) workbook.close();
}
}
// 辅助方法:安全获取字符串值,兼容 STRING、NUMERIC、BLANK 等类型
private String getCellStringValue(Cell cell) {
if (cell == null) return null;
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 BLANK:
return "";
default:
return cell.toString().trim();
}
}
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");
// 更稳定的定位方式(避免绝对XPath)
driver.findElement(By.id("identifierId")).sendKeys(username);
driver.findElement(By.id("identifierNext")).click(); // 替换为语义化ID
// 显式等待密码框出现(推荐配合 WebDriverWait)
Thread.sleep(2000); // 简化示例,生产环境请用 WebDriverWait
driver.findElement(By.name("Passwd")).sendKeys(password); // 改用 name 属性更稳定
driver.findElement(By.id("passwordNext")).click();
// 可添加断言验证登录成功(如检查URL或元素)
Thread.sleep(3000);
} catch (Exception e) {
e.printStackTrace();
} 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");
}
}通过以上修正与增强,您的数据驱动框架将具备生产级稳定性与可维护性。记住:一个健壮的自动化框架,始于对每一个 null 的敬畏,成于对每一处资源的负责。