从Excel文件读取/写入数据

文件IO是任何软件过程的关键部分。我们经常创建一个文件我们需要一个进程来使用Selenium操作文件。 Java为我们提供了使用Selenium进行文件操作的不同类。在本教程中,我们将学习如何读写Excel。

Selenium中的Apache POI

这个Selenium中的Apache POI是广泛使用的用于Selenium数据驱动测试的API。它是一个用Java编写的POI库,它为用户提供了POI代表“非友好的混淆实现”。

  • 如何使用POI(Maven POM依赖)处理EXCEL文件
  • POI中的类和接口
  • 读/写操作
  • 从Excel文件读取数据
  • 将数据写入Excel文件
  • 使用JXL API操作Excel

导出Excel

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

How to export Excel File in Selenium Webdriver using Aapache POI
How to export Excel File in Selenium Webdriver using Aapache POI

为了用Java读写Excel文件,Apache提供了一个非常著名的POI库。此库足够读写两个库XLS和xlsxExcel的文件格式。 如果在项目中使用Maven,则Maven依赖项将为

How to export Excel File in Selenium Webdriver using Aapache POI
How to export Excel File in Selenium Webdriver using Aapache POI
 <dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>4.1.1</version>
</dependency>
 

或者,也可以简单地从以下地址下载最新版本的POI JAR http://poi.apache.org/download.html http://poi.apache.org/download.html下载最新的zip文件(&D)

How to download Apache POI
How to download Apache POI

下载此JAR的zip文件时,需要将其解压缩并将所有JAR添加到项目的类路径中。

How to download Apache POI
How to download Apache POI

POI中的类和接口:

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

以下是中的不同Java接口和类的列表POI用于阅读XLS和xlsx文件-

Workbook:XSSFWorkbook和HSSFWorkbook类实现此接口。 XSSFWorkbook:是xlsx文件的类表示。 HSSFWorkbook:是XLS文件的类表示形式。 Sheet:XSSFSheet和HSSFSheet类实现此接口。 XSSFSheet:是表示xlsx文件中的工作表的类。 HSSFSheet:是表示XLS文件中的工作表的类。 Row:XSSFRow和HSSFRow类实现此接口。 XSSFRow:是表示xlsx文件表中的一行的类。 HSSFRow:是表示XLS文件工作表中的一行的类。 Cell:XSSFCell和HSSFCell类实现此接口。 XSSF Cell:是表示xlsx文件行中的一个单元格的类。 HSSFCell:是一个类,表示XLS文件行中的一个单元格。

读/写操作-

对于示例,考虑下面给定的Excel文件格式

Read/Write Data from Excel File in Selenium Webdriver
Read/Write Data from Excel File in Selenium Webdriver

从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 ReadExcelFile {
    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");
    }
}
 

注意:在这里,我们不使用 Test NG框架。使用Selenium中的函数read excel将类作为Java应用程序运行,如上面的示例所示。

Read/Write Data from Excel File in Selenium Webdriver
Read/Write Data from Excel File in Selenium Webdriver

将数据写入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 WriteExcelFile {
    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);
    }
}
 
Read/Write Data from Excel File in Selenium Webdriver
Read/Write Data from Excel File in Selenium Webdriver

使用JXL API操作Excel

How to manipulate Excel File using JXL API
How to manipulate Excel File using JXL API

JXL也是用Java读取Excel文件和写入文件的另一个著名的JAR。如今,POI用于这是一个非常小且简单的API,用于在Selenium中读取EXCEL。

下载JXL:

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

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

How to manipulate Excel File using JXL API
How to manipulate Excel File using JXL API

还可以在这个用于JXL的压缩文件中获得演示示例。

其中一些功能:

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

缺点:

  • 只能编写Excel 97和更高版本(不支持用Excel 95编写)。
  • JXL不支持EXCEL文件的xlsx格式。
  • 它生成Excel2000格式的电子表格。

总结:

  • 可以通过Java IO操作读取Excel文件。为此,我们需要使用Apache POI Jar。
  • Excel文件中有两种工作簿,xlsx和XLS文件。
  • POI具有不同的界面工作簿、工作表、行和单元格。
  • 这些接口由对应的XLS(HSSFWorkbook、HSSFSheet、HSSFRow、HSSFCell)和xlsx(XSSFWorkbook、XSSFSheet、XSSFRow、XSSFCell)文件操作类。
  • JXL是用于在Selenium中处理Excel的另一个API。
  • JXL无法使用xlsx格式的excel。

IT赶路人

专注IT知识分享