如何从 Excel 文件中读/写数据:Selenium POI

文件 IO 是任何软件流程的关键部分。我们经常在电脑中创建文件、打开并更新或删除文件。Selenium 自动化也是如此。我们需要一个用 Selenium 操作文件的过程。

Java 为我们提供了不同的类,用于使用 Selenium 进行文件操作。在本教程中,我们将学习如何借助 Java IO 包和 Apache POI 库,在 Excel 文件上进行读写操作。

Selenium 中的 Apache POI

Selenium 中的 Apache POI 是用于 Selenium 数据驱动测试的广泛使用的 API。它是一个用 Java 编写的 POI 库,为用户提供了一个用于操作 Microsoft 文档(如 .xls 和 .xlsx)的 API。用户可以轻松创建、修改和读/写 Excel 文件。POI 代表“Poor Obfuscation Implementation”。

导出 Excel

如何使用 POI 处理 Excel 文件(Maven POM 依赖)

Handle Excel File Using POI

要在 Java 中读写 Excel 文件,Apache 提供了一个非常著名的库 POI。该库足以读写 Excel 的 **XLS** 和 **XLSX** 文件格式。

POI 库提供了 **HSSF** 实现来读取 **XLS** 文件。

要读取 **XLSX**,**POI 库**的 **XSSF** 实现将是首选。让我们详细研究这些实现。

如果您在项目中使用 Maven,Maven 依赖将是

Handle Excel File Using POI

<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>4.1.1</version>
</dependency>

或者您可以简单地从 http://poi.apache.org/download.html 下载最新版本的 POI jar 包并下载最新的 zip 文件

Handle Excel File Using POI

当您下载此 jar 文件的 zip 文件时,您需要解压它并将所有这些 jar 添加到项目的类路径中。

Handle Excel File Using POI

POI 中的类和接口

Classes and Interfaces in Apache POI
Apache POI 中的类和接口

以下是用于读取 **XLS** 和 **XLSX** 文件的 **POI** 中不同 Java 接口和类的列表:

  • Workbook:XSSFWorkbook 和 HSSFWorkbook 类实现了此接口。
  • XSSFWorkbook:是 XLSX 文件的类表示。
  • HSSFWorkbook:是 XLS 文件的类表示。
  • Sheet:XSSFSheet 和 HSSFSheet 类实现了此接口。
  • XSSFSheet:是表示 XLSX 文件中工作表的类。
  • HSSFSheet:是表示 XLS 文件中工作表的类。
  • Row:XSSFRow 和 HSSFRow 类实现了此接口。
  • XSSFRow:是表示 XLSX 文件工作表中行的类。
  • HSSFRow:是表示 XLS 文件工作表中行的类。
  • Cell:XSSFCell 和 HSSFCell 类实现了此接口。
  • XSSFCell:是表示 XLSX 文件行中单元格的类。
  • HSSFCell:是表示 XLS 文件行中单元格的类。

读/写操作

对于我们的示例,我们将考虑以下给定的 Excel 文件格式

Read Write Operation

从 Excel 文件读取数据

完整示例:这里我们尝试从 Selenium 中的 Excel 读取数据

package excelExportAndFileIO;

import java.io.File;

import java.io.FileInputStream;

import java.io.IOException;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;

import org.apache.poi.ss.usermodel.Row;

import org.apache.poi.ss.usermodel.Sheet;

import org.apache.poi.ss.usermodel.Workbook;

import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class ReadGuru99ExcelFile {

    public void readExcel(String filePath,String fileName,String sheetName) throws IOException{

    //Create an object of File class to open xlsx file

    File file =    new File(filePath+"\\"+fileName);

    //Create an object of FileInputStream class to read excel file

    FileInputStream inputStream = new FileInputStream(file);

    Workbook guru99Workbook = null;

    //Find the file extension by splitting file name in substring  and getting only extension name

    String fileExtensionName = fileName.substring(fileName.indexOf("."));

    //Check condition if the file is xlsx file

    if(fileExtensionName.equals(".xlsx")){

    //If it is xlsx file then create object of XSSFWorkbook class

    guru99Workbook = new XSSFWorkbook(inputStream);

    }

    //Check condition if the file is xls file

    else if(fileExtensionName.equals(".xls")){

        //If it is xls file then create object of HSSFWorkbook class

        guru99Workbook = new HSSFWorkbook(inputStream);

    }

    //Read sheet inside the workbook by its name

    Sheet guru99Sheet = guru99Workbook.getSheet(sheetName);

    //Find number of rows in excel file

    int rowCount = guru99Sheet.getLastRowNum()-guru99Sheet.getFirstRowNum();

    //Create a loop over all the rows of excel file to read it

    for (int i = 0; i < rowCount+1; i++) {

        Row row = guru99Sheet.getRow(i);

        //Create a loop to print cell values in a row

        for (int j = 0; j < row.getLastCellNum(); j++) {

            //Print Excel data in console

            System.out.print(row.getCell(j).getStringCellValue()+"|| ");

        }

        System.out.println();
    } 

    }  

    //Main function is calling readExcel function to read data from excel file

    public static void main(String...strings) throws IOException{

    //Create an object of ReadGuru99ExcelFile class

    ReadGuru99ExcelFile objExcelFile = new ReadGuru99ExcelFile();

    //Prepare the path of excel file

    String filePath = System.getProperty("user.dir")+"\\src\\excelExportAndFileIO";

    //Call read file method of the class to read data

    objExcelFile.readExcel(filePath,"ExportExcel.xlsx","ExcelGuru99Demo");

    }

}

注意:我们在这里没有使用 Testng 框架。使用函数在 Selenium 中读取 excel,如上例所示,将该类作为 Java 应用程序运行。

Read Data from Excel File

在 Excel 文件上写入数据

完整示例:这里我们尝试通过在 Excel 文件中添加新行来从 Excel 文件写入数据

package excelExportAndFileIO;

import java.io.File;

import java.io.FileInputStream;

import java.io.FileOutputStream;

import java.io.IOException;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;

import org.apache.poi.ss.usermodel.Cell;

import org.apache.poi.ss.usermodel.Row;

import org.apache.poi.ss.usermodel.Sheet;

import org.apache.poi.ss.usermodel.Workbook;

import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class WriteGuru99ExcelFile {

    public void writeExcel(String filePath,String fileName,String sheetName,String[] dataToWrite) throws IOException{

        //Create an object of File class to open xlsx file

        File file =    new File(filePath+"\\"+fileName);

        //Create an object of FileInputStream class to read excel file

        FileInputStream inputStream = new FileInputStream(file);

        Workbook guru99Workbook = null;

        //Find the file extension by splitting  file name in substring and getting only extension name

        String fileExtensionName = fileName.substring(fileName.indexOf("."));

        //Check condition if the file is xlsx file

        if(fileExtensionName.equals(".xlsx")){

        //If it is xlsx file then create object of XSSFWorkbook class

        guru99Workbook = new XSSFWorkbook(inputStream);

        }

        //Check condition if the file is xls file

        else if(fileExtensionName.equals(".xls")){

            //If it is xls file then create object of XSSFWorkbook class

            guru99Workbook = new HSSFWorkbook(inputStream);

        }    

    //Read excel sheet by sheet name    

    Sheet sheet = guru99Workbook.getSheet(sheetName);

    //Get the current count of rows in excel file

    int rowCount = sheet.getLastRowNum()-sheet.getFirstRowNum();

    //Get the first row from the sheet

    Row row = sheet.getRow(0);

    //Create a new row and append it at last of sheet

    Row newRow = sheet.createRow(rowCount+1);

    //Create a loop over the cell of newly created Row

    for(int j = 0; j < row.getLastCellNum(); j++){

        //Fill data in row

        Cell cell = newRow.createCell(j);

        cell.setCellValue(dataToWrite[j]);

    }

    //Close input stream

    inputStream.close();

    //Create an object of FileOutputStream class to create write data in excel file

    FileOutputStream outputStream = new FileOutputStream(file);

    //write data in the excel file

    guru99Workbook.write(outputStream);

    //close output stream

    outputStream.close();
	
    }

    public static void main(String...strings) throws IOException{

        //Create an array with the data in the same order in which you expect to be filled in excel file

        String[] valueToWrite = {"Mr. E","Noida"};

        //Create an object of current class

        WriteGuru99ExcelFile objExcelFile = new WriteGuru99ExcelFile();

        //Write the file using file name, sheet name and the data to be filled

        objExcelFile.writeExcel(System.getProperty("user.dir")+"\\src\\excelExportAndFileIO","ExportExcel.xlsx","ExcelGuru99Demo",valueToWrite);

    }

}

Write Data On Excel File

使用 JXL API 操作 Excel

Excel Manipulation Using JXL API

JXL 也是另一个著名的 jar 包,用于在 Java 中读取 Excel 文件和写入文件。如今,POI 在大多数项目中都得到使用,但在 POI 之前,JXL 是唯一用于 Excel 操作的 Java API。它是一个非常小巧简单的 API,用于在 Selenium 中读取 Excel。

提示:我建议不要在任何新项目中使用 JXL,因为该库自 2010 年以来一直没有活跃开发,并且与 POI API 相比缺乏功能。

下载 JXL

如果您想使用 JXL,可以从以下链接下载:

https://sourceforge.net/projects/jexcelapi/files/jexcelapi/2.6.12/

Excel Manipulation Using JXL API

您还可以在此压缩文件中找到 JXL 的演示示例。

一些功能

  • JXL 能够读取 95、97、2000、XP、2003 工作簿的 Selenium Excel 文件。
  • 我们可以使用英语、法语、西班牙语、德语。
  • 在 Excel 中复制图表和插入图像是可能的

缺点

  • 我们只能写入 Excel 97 及更高版本(不支持写入 Excel 95)。
  • JXL 不支持 Excel 文件的 XLSX 格式。
  • 它生成 Excel 2000 格式的电子表格。

摘要

  • Excel 文件可以通过 Java IO 操作读取。为此,我们需要使用 **Apache POI Jar**。
  • Excel 文件中有两种工作簿,**XLSX** 和 **XLS** 文件。
  • POI 具有不同的接口:Workbook、Sheet、Row、Cell。
  • 这些接口由相应的 **XLS** (**HSSFWorkbook、HSSFSheet、HSSFRow、HSSFCell**) 和 **XLSX** (**XSSFWorkbook、XSSFSheet、XSSFRow、XSSFCell**) 文件操作类实现。
  • JXL 是另一个用于 Selenium 中 Excel 处理的 API。
  • JXL 无法处理 Excel 的 XLSX 格式。