如何使用 Selenium 的 Apache POI 集成基于单元格属性关键字从 Excel 工作表中读取单元格值

问题描述

Example of Excel Data

我需要使用单元格引用属性(以蓝色突出显示)读取上述示例数据

工作表中的表格按列顺序维护。

例如,如果表格是这样的:

名字 尼克 杰克
姓氏 愤怒 瑞恩
个人邮箱 nick-fury@example.com jack-ryan@example.com

然后我希望脚本运行:

名字 尼克
姓氏 愤怒
个人邮箱 nick-fury@example.com

然后运行:

名字 杰克
姓氏 瑞恩
个人邮箱 jack-ryan@example.com

并且可以在我的 ExcelReader 类代码中使用相应的属性firstNamelastNamepersonalEmail)进行访问。

这是我想知道的:

  1. 有没有办法使用 Java 的 Apache-poi 扩展来实现这一点?
  2. 我可以从 apache-poi 扩展中使用哪些函数库?
  3. 我应该在实用程序包中使用什么代码

提前致谢:)

解决方法

要解决这个问题,您需要反转数据获取逻辑。 所以这里我们首先需要获取列数据,然后遍历它的所有行。

即。 Nick -> Fury -> nick-fury@example.com 然后移动到另一列并获取 Jack -> Ryan -> jack-ryan@example.com

截图:

enter image description here

重要提示:

此代码是使用POI获取xls文件数据,请将代码更改为 根据您的要求。

(1)。 HSSFWorkbook:这个类有读取的方法 并以 .xls 格式写入 Microsoft Excel 文件。

(2).XSSFWorkbook:这个类有读写微软的方法 .xls 或 .xlsx 格式的 Excel 和 OpenOffice xml 文件。

代码:

@Test(dataProvider = "getExcelData")
    public void testSheet(String firstName,String lastName,String personalEmail) {

    System.out.println(firstName+"  "+lastName+" "+personalEmail);
}

@DataProvider
public Object[][] getExcelData(){
    String excelSheetPath = System.getProperty("user.dir")+"/data.xls";
    String sheetName = "Sheet1";
    return getExcelData(excelSheetPath,sheetName);
}

public Object[][] getExcelData(String excelSheetPath,String sheetName) {
    Object[][] arrayExcelData = null;
    try (
            FileInputStream fileStream = new FileInputStream(excelSheetPath)
    ) {
        HSSFWorkbook workbook = new HSSFWorkbook(fileStream);
        HSSFSheet sheet = workbook.getSheet(sheetName);
        Row row = sheet.getRow(0);
        int lastRowIndex = sheet.getLastRowNum() + 1;
        System.out.println("Last row index :" + lastRowIndex);
        int totalNoOfCols = row.getLastCellNum() - 1;
        System.out.println("Total columns :" + totalNoOfCols);

        arrayExcelData = new Object[totalNoOfCols][lastRowIndex];
        DataFormatter df = new DataFormatter();

        for (int i = 1; i <= totalNoOfCols ; i++) {
            for (int j = 0; j < lastRowIndex; j++) {
                row = sheet.getRow(j);
                Cell c = row.getCell(i);
                String cellData = df.formatCellValue(c);
                System.out.println(cellData);
                arrayExcelData[i-1][j] = cellData;
            }
            System.out.println("-----------");
        }
    } catch (Exception e) {
        e.printStackTrace();
        System.out.println(e.getMessage());
    }
    return arrayExcelData;
}