• Selenium Video Tutorials

Selenium WebDriver - Excel 資料檔案



Selenium Webdriver 可用於與 Excel 資料檔案互動。在自動化測試中,通常需要透過 Excel 檔案為測試用例提供大量資料。這樣做是為了驗證特定場景或建立資料驅動框架

Java 提供了大量的類和方法,可以使用 Apache POI 庫對 Excel 檔案執行讀寫資料操作。Apache POI API 是一組免費且開源的Java 庫。

什麼是 Apache POI?

Apache POI 用於處理 Microsoft 檔案。它可以用於對各種格式的檔案(包括 Excel)執行讀取、寫入、更新和其他操作。Java 不能直接用於處理 Excel 檔案,因此 Apache POI(第三方 API)與 Java 一起使用,以建立需要從 Excel 中讀取資料的 Selenium 測試。

可以使用 Apache POI 的 Workbook 介面處理 Excel 工作簿。此介面利用 WorkBookFactory 類來生成特定的工作簿。HSSFWorkbook 類(實現 Workbook 介面)具有有助於對具有 .xls 格式的Microsoft Excel 檔案執行讀寫操作的方法。XSSFWorkbook 類(實現 Workbook 介面)具有有助於對具有 .xlsx 或 .xls 格式的 Microsoft Excel 和 OpenOffice XML 檔案執行讀寫操作的方法。

類似地,可以使用 Apache POI 的 Sheet 介面處理 Excel 工作表。HSSFSheet 類(實現 Sheet 介面)具有在 HSSFWorkbook 工作簿(具有 .xls 格式的 Microsoft Excel 檔案)中建立工作表的方法。XSSFSheet 類(實現 Sheet 介面)具有在 XSSFWorkbook 工作簿(具有 .xlsx 或 .xls 格式的 Microsoft Excel 和 OpenOffice XML 檔案)中建立工作表的方法。

可以使用 Apache POI 的 Row 介面處理 Excel 行。HSSFRow 類(實現 Row 介面)具有表示 HSSFSheet 中行的的方法。XSSFRow 類(實現 Row 介面)具有表示 XSSFSheet 中行的的方法。

可以使用 Apache POI 的 Cell 介面處理 Excel 單元格。HSSFCell 類(實現 Row 介面)具有處理 HSSFRow 中單元格的方法。XSSFCell 類(實現 Row 介面)具有處理 XSSFRow 中單元格的方法。

如何安裝 Apache POI?

步驟 1 - 從連結 Apache POI Common 將 Apache POI Common 依賴項新增到 pom.xml 檔案。

步驟 2 - 從連結 Apache POI API Based 將基於 OPC 和 OOXML 架構的 Apache POI API 依賴項新增到 pom.xml 檔案。

步驟 3 - 儲存包含所有依賴項的 pom.xml 並更新Maven 專案。

讀取 Excel 中的所有值

讓我們以名為 Details.xlsx 的 Excel 檔案為例,我們將讀取整個 Excel 檔案並檢索其所有值。

Selenium Excel Data File 1

請注意:Details.xlsx 檔案放置在專案下的 Resources 資料夾中,如下圖所示。

Selenium Excel Data File 2

示例

package org.example;

import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

public class ExcelRead {
   public static  void main(String args[]) throws IOException {

      // identify location of .xlsx file
      File f = new File("./Resources/Details.xlsx");
      FileInputStream i = new FileInputStream(f);

      // instance of XSSFWorkbook
      XSSFWorkbook w = new XSSFWorkbook(i);

      // create sheet in XSSFWorkbook with name Details1
      XSSFSheet s = w .getSheet("Details1");

      // handle total rows in XSSFSheet
      int r = s.getLastRowNum() - s.getFirstRowNum();

      // loop through rows
      for(int k = 0; k <= r ; k++){
      
         // get cells in each row
         int c = s.getRow(k).getLastCellNum();

         for(int j = 0; j < c; j++){
         
            // get cell values
            System.out.println(s.getRow(k).getCell(j).getStringCellValue());
         }
      }
   }
}

新增到 pom.xml 的依賴項。

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 
   http://maven.apache.org/xsd/maven-4.0.0.xsd">

   <modelVersion>4.0.0</modelVersion>
   <groupId>org.example</groupId>
   <artifactId>SeleniumJava</artifactId>
   <version>1.0-SNAPSHOT</version>

   <properties>
      <maven.compiler.source>16</maven.compiler.source>
      <maven.compiler.target>16</maven.compiler.target>
      <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
   </properties>

   <!-- https://mvnrepository.com/artifact/org.seleniumhq.selenium/selenium-java -->
   <dependencies>
      <dependency>
         <groupId>org.seleniumhq.selenium</groupId>
         <artifactId>selenium-java</artifactId>
         <version>4.11.0</version>
      </dependency>

      <!-- https://mvnrepository.com/artifact/org.apache.poi/poi -->
      <dependency>
         <groupId>org.apache.poi</groupId>
         <artifactId>poi</artifactId>
         <version>5.2.5</version>
      </dependency>

      <!-- https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml -->
      <dependency>
         <groupId>org.apache.poi</groupId>
         <artifactId>poi-ooxml</artifactId>
         <version>5.2.5</version>
      </dependency>
   </dependencies>
</project>

輸出

Name
Street
Ram
Street 12
Rohan
Street 110

Process finished with exit code 0

在上面的示例中,我們讀取了整個 Excel 檔案,並在控制檯中獲得了其所有值。

最後,收到訊息 Process finished with exit code 0,表示程式碼已成功執行。

讀取和寫入 Excel 中的值

讓我們以名為 DetailsStudent.xlsx 的 Excel 檔案為例,我們將從該 Excel 檔案中讀取值,並將這些資料輸入到下面的註冊頁面中。成功後,我們將文字 Test Case: Pass 寫入單元格(同一行和 E 列)。如果未成功完成,我們將文字 Test Case: Fail 寫入同一單元格。

Selenium Excel Data File 3

下圖顯示了我們將從 DetailsStudent.xlsx 檔案中在 Full Name:Last Name:Username:Password 欄位中輸入資料的註冊頁面。

Selenium Excel Data File 4

請注意 - DetailsStudent.xlsx Excel 檔案放置在專案下的 Resources 資料夾中,如下圖所示。

Selenium Excel Data File 5

示例

package org.example;

import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

public class ExcelReadWrite {
   public static  void main(String args[]) throws IOException {

      // identify location of .xlsx file
      File f = new File("./Resources/DetailsStudent.xlsx");
      FileInputStream i = new FileInputStream(f);

      // instance of XSSFWorkbook
      XSSFWorkbook w = new XSSFWorkbook(i);

      // create sheet in XSSFWorkbook with name Details1
      XSSFSheet s = w .getSheet("Details1");

      // handle total rows in XSSFSheet
      int r = s.getLastRowNum() - s.getFirstRowNum();

      // Initiate the Webdriver
      WebDriver driver = new ChromeDriver();

      // adding implicit wait of 15 secs
      driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);

      // Opening the webpage where we will identify elements
      driver.get("https://tutorialspoint.tw/selenium/practice/register.php#");

      //Identify elements for registration
      WebElement fname = driver.findElement(By.xpath("//*[@id='firstname']"));
      WebElement lname = driver.findElement(By.xpath("//*[@id='lastname']"));
      WebElement uname = driver.findElement(By.xpath("//*[@id='username']"));
      WebElement pass = driver.findElement(By.xpath("//*[@id='password']"));
      WebElement btn = driver.findElement(By.xpath("//*[@id='signupForm']/div[5]/input"));

      // loop through rows, read and enter values in form
      for(int j = 1; j <= r; j++) {
         fname.sendKeys(s.getRow(j).getCell(0).getStringCellValue());
         lname.sendKeys(s.getRow(j).getCell(1).getStringCellValue());
         uname.sendKeys(s.getRow(j).getCell(2).getStringCellValue());
         pass.sendKeys(s.getRow(j).getCell(3).getStringCellValue());

         // submit registration form
         btn.click();

         // verify form submitted
         WebElement fname1 = driver.findElement(By.xpath("//*[@id='firstname']"));
         String value = fname1.getAttribute("value");

         // create cell at Column 4 to write values in excel
         XSSFCell c = s.getRow(j).createCell(4);

         // write results in excel
         if (value.isEmpty()) {
            c.setCellValue("Test Case: PASS");
         } else {
            c.setCellValue("Test Case: FAIL");
         }

         // complete writing value in excel
         FileOutputStream o = new FileOutputStream("./Resources/DetailsStudent.xlsx");
         w.write(o);
      }

      // closing workbook object
      w.close();

      // Quitting browser
      driver.quit();
   }
}

新增到 pom.xml 的依賴項。

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 
   http://maven.apache.org/xsd/maven-4.0.0.xsd">

   <modelVersion>4.0.0</modelVersion>
   <groupId>org.example</groupId>
   <artifactId>SeleniumJava</artifactId>
   <version>1.0-SNAPSHOT</version>

   <properties>
      <maven.compiler.source>16</maven.compiler.source>
      <maven.compiler.target>16</maven.compiler.target>
      <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
   </properties>

   <!-- https://mvnrepository.com/artifact/org.seleniumhq.selenium/selenium-java -->
   <dependencies>
      <dependency>
         <groupId>org.seleniumhq.selenium</groupId>
         <artifactId>selenium-java</artifactId>
         <version>4.11.0</version>
      </dependency>

      <!-- https://mvnrepository.com/artifact/org.apache.poi/poi -->
      <dependency>
         <groupId>org.apache.poi</groupId>
         <artifactId>poi</artifactId>
         <version>5.2.5</version>
      </dependency>

      <!-- https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml -->
      <dependency>
         <groupId>org.apache.poi</groupId>
         <artifactId>poi-ooxml</artifactId>
         <version>5.2.5</version>
      </dependency>
   </dependencies>
</project>

輸出

Process finished with exit code 0

在上面的示例中,我們讀取了整個 Excel 檔案,並在第五列的單元格中寫入值 Test Case: Pass

最後,收到訊息 Process finished with exit code 0,表示程式碼已成功執行。

Selenium Excel Data File 6

如上圖所示,測試執行後,在與Excel中註冊資料相同的Excel檔案**DetailsStudent.xlsx**的第5列中寫入**測試用例:透過**。

結論

本教程全面介紹了Selenium Webdriver Excel資料檔案。我們首先介紹了什麼是Apache POI,如何安裝Apache POI,並透過示例演示瞭如何在Selenium Webdriver的幫助下使用Apache POI讀取和寫入Excel中的值。這將使您深入瞭解Selenium Webdriver中的Excel資料檔案。建議您多練習所學內容,並探索與Selenium相關的其他內容,以加深理解並拓寬視野。

廣告