엑셀 데이터 읽기/쓰기 방법 Selenium Apache POI 사용

⚡ 스마트 요약

엑셀 파일 드라이브 Selenium 데이터 기반 테스트, 그리고 Apache POI는 바로 그것입니다. Java 이 라이브러리는 해당 파일을 읽고 쓰는 데 사용됩니다. 아래 섹션에서는 의존성, 핵심 클래스, 읽기 및 쓰기 예제, 그리고 JXL에 대해 설명합니다.

  • 🔘 두 가지 형식: HSSF 클래스는 .xls 파일을 처리하고, XSSF 클래스는 .xlsx 파일을 처리합니다.
  • 핵심 인터페이스: 통합 문서, 시트, 행 및 셀은 스프레드시트를 그대로 반영합니다.
  • 🧪 독서: FileInputStream과 getLastRowNum을 함께 사용하면 모든 행과 셀을 순회합니다.
  • 🛠️ 쓰기: createRow와 setCellValue는 데이터를 추가하고, FileOutputStream은 이를 저장합니다.
  • 📊 유산: JXL은 이전 통합 문서를 읽을 수 있지만 XLSX는 읽을 수 없습니다.

엑셀 데이터 읽기 및 쓰기 Selenium 아파치 POI와 함께

파일 IO는 모든 소프트웨어 프로세스에서 중요한 부분입니다. 우리는 컴퓨터에서 자주 파일을 생성하고, 열고, 업데이트하거나 삭제합니다. 의 경우도 마찬가지다 Selenium 오토메이션. 파일을 조작하는 프로세스가 필요합니다. Selenium.

Java 파일 조작을 위한 다양한 클래스를 제공합니다. Selenium. 이번 튜토리얼에서는 어떻게 읽고 쓰는지 배워보겠습니다. 뛰어나다 의 도움으로 파일 Java IO 패키지 및 아파치 POI 도서관.

아파치 POI Selenium

The 아파치 POI Selenium 널리 사용되는 API입니다. Selenium 데이터 기반 테스트이것은 POI 라이브러리이며 다음 언어로 작성되었습니다. Java 사용자에게 조작을 위한 API를 제공합니다. Microsoft .xls 및 .xlsx와 같은 문서 파일입니다. 사용자는 Excel 파일을 쉽게 생성, 수정 및 읽고 쓸 수 있습니다. POI는 "엉성한 난독화 구현(Poor Obfuscation Implementation)"의 약자입니다.

POI를 사용하여 Excel 파일을 처리하는 방법 (Maven POM 종속성)

POI는 다음과 같은 링크를 제공합니다. Selenium 아래 통합 문서에 대한 테스트입니다.

Apache POI는 다음과 같은 역할을 합니다. Selenium 테스트 및 엑셀 통합 문서

Excel 파일을 읽고 쓰려면 JavaApache는 매우 유명한 라이브러리인 POI를 제공합니다. 이 라이브러리는 Excel의 XLS 및 XLSX 파일 형식을 모두 읽고 쓸 수 있는 기능을 갖추고 있습니다.

XLS 파일을 읽기 위해 POI 라이브러리에서 HSSF 구현을 제공합니다.

XLSX 파일을 읽으려면 POI 라이브러리의 XSSF 구현체를 사용하는 것이 좋습니다. 이제 이러한 구현체들을 자세히 살펴보겠습니다.

프로젝트에서 Maven을 사용하는 경우, 아래와 같이 pom.xml 파일에 Maven 종속성이 추가됩니다.

Maven 프로젝트의 pom.xml 파일에 POI 종속성 항목이 추가되었습니다.

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

버전 참고: 4.1.1은 원래 예제이며, 현재 프로젝트에서는 다음과 같이 선언합니다. poi-ooxml XLSX 파일에 필요한 5.5.1 버전입니다.

또는 다음에서 최신 버전의 POI jar를 다운로드할 수 있습니다. http://poi.apache.org/download.html & 최신 zip 파일 다운로드

Apache POI 다운로드 페이지는 바이너리 및 소스 배포 아카이브 목록을 제공합니다.

이 jar의 zip 파일을 다운로드할 때 압축을 풀고 이러한 모든 jar를 프로젝트의 클래스 경로에 추가해야 합니다.

압축 해제된 POI jar 파일이 추가되었습니다. Java 프로젝트 빌드 경로

POI의 클래스 및 인터페이스

다음은 다양한 목록입니다 Java POI에서 XLS 및 XLSX 파일을 읽기 위한 인터페이스와 클래스는 아래와 같습니다.

워크북에서 시트, 행, 셀까지 POI 클래스 계층 구조가 표시됩니다.

  • 학습장: XSSFWorkbook 및 HSSFWorkbook 클래스는 이 인터페이스를 구현합니다.
  • XSSF워크북: XLSX 파일의 클래스 표현입니다.
  • HSSF워크북: XLS 파일의 클래스 표현입니다.
  • 시트 : XSSFSheet 및 HSSFSheet 클래스는 이 인터페이스를 구현합니다.
  • XSSF시트: XLSX 파일의 시트를 나타내는 클래스입니다.
  • HSSFSheet: XLS 파일의 시트를 나타내는 클래스입니다.
  • 열: XSSFRow 및 HSSFRow 클래스는 이 인터페이스를 구현합니다.
  • XSSFRow: XLSX 파일 시트의 행을 나타내는 클래스입니다.
  • HSSFRow: XLS 파일 시트의 행을 나타내는 클래스입니다.
  • 세포: XSSFCell 및 HSSFCell 클래스는 이 인터페이스를 구현합니다.
  • XSSFCell: XLSX 파일의 한 행에 있는 셀을 나타내는 클래스입니다.
  • HSSFC셀: XLS 파일 행의 셀을 나타내는 클래스입니다.

읽기 / 쓰기 Opera기

이 예에서는 아래 주어진 Excel 파일 형식을 고려합니다.

Excel 파일이 포함된 ExportExcel 통합 문서 샘플Guru두 예제 모두에서 사용된 99Demo 시트

Excel 파일에서 데이터 읽기

전체 예시: 여기서는 엑셀에서 데이터를 읽어오려고 합니다. Selenium:

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 여기에 프레임워크가 있습니다. 다음과 같이 수업을 실행하세요. Java Excel 읽기 기능을 사용하는 응용 프로그램 Selenium 위의 예에 표시된 것처럼.

그러면 콘솔에 각 행이 셀 단위로 출력됩니다.

콘솔 출력은 각 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);

    }

}

그러면 통합 문서에는 추가된 행이 포함됩니다.

E씨와 노이다가 포함된 새 행이 엑셀 시트에 추가되었습니다.

JXL API를 사용한 Excel 조작

JXL은 Excel 파일을 읽을 수 있는 또 다른 유명한 jar입니다. Java 그리고 파일 쓰기. 요즘은 대부분의 프로젝트에서 POI를 사용하지만 POI 이전에는 JXL만이 사용 가능했습니다. Java Excel 조작을 위한 API입니다. Excel 읽기를 위한 매우 작고 간단한 API입니다. Selenium.

프로젝트 라이브러리 목록에 JXL jar 파일이 포함되어 있습니다.

도움말 : 제 생각에는 JXL은 2010년 이후로 활발한 개발이 중단되었고(최신 버전이 2.6.12입니다), POI API에 비해 기능이 부족하기 때문에 새로운 프로젝트에서는 사용하지 않는 것이 좋습니다.

JXL 다운로드:

JXL로 작업하려면 이 링크에서 다운로드할 수 있습니다.

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

이 압축 파일 안에는 JXL 데모 예제도 포함되어 있습니다.trac아래에 내용이 표시됩니다.

Extracted JXL 아카이브에는 jar, 문서 및 데모 폴더가 표시됩니다.

일부 기능 :

  • JXL은 Excel 파일을 읽을 수 있습니다. Selenium 95, 97, 2000, XP, 2003 통합 문서의 경우.
  • 우리는 영어, 프랑스어, 스페인어, 독일어로 작업할 수 있습니다.
  • 차트 복사 및 엑셀 이미지 삽입이 가능합니다.

약점:

  • Excel 97 이상에서만 작성할 수 있습니다(Excel 95에서는 작성할 수 없습니다).
  • JXL은 Excel 파일의 XLSX 형식을 지원하지 않습니다.
  • Excel 2000 형식으로 스프레드시트를 생성합니다.

자주 묻는 질문

선언 포이-오오크람poi만 사용하는 것이 아닙니다. poi를 간접적으로 불러와 XLSX에 필요한 XSSF 클래스를 제공합니다. 현재 버전은 5.5.1입니다.

POI의 OOXML 부분이 누락되었거나 일치하지 않습니다. poi-ooxml을 추가하고 모든 POI 아티팩트를 단일 버전으로 유지하세요. 여러 버전이 혼합되어 있으면 스키마 클래스가 경로에서 누락됩니다.

getStringCellValue는 텍스트 셀에서만 작동합니다. 모든 셀을 문자열로 읽으려면 DataFormatter를 사용하거나 getCellType을 확인하고 수식에 FormulaEvaluator를 호출하세요.

행이나 셀이 누락되면 null이 반환되므로 루프에서 NullPointerException이 발생합니다. 먼저 null 또는 CellType.BLANK인지 확인하거나, MissingCellPolicy를 설정하여 빈 셀이 반환되도록 하십시오.

머신러닝 모델은 현실적인 행을 생성하고, 중복을 표시하고, 결함을 가장 잘 드러내는 조합의 순위를 매기고, 불필요한 부분을 제거합니다. 데이터 기반 테스트 시트.

GitHub 부조종사 댓글에서 독자와 작성자를 위한 정형화된 문구를 초안합니다. Rev살펴보세요. 이전 POI 릴리스에서 더 이상 사용되지 않는 세포 유형 상수를 나타내는 경우가 많기 때문입니다.

SXSSFWorkbook은 통합 문서를 메모리에 저장하는 대신 행을 디스크에 스트리밍 방식으로 저장하므로 대용량 내보내기 시 OutOfMemoryError 오류가 발생하지 않습니다. 읽기 시에는 루프 내에서 행을 처리하십시오.

src/test/resources 아래에 경로를 유지하고 System.getProperty("user.dir")에서 경로를 구성하세요. 절대 경로는 테스트 스위트가 다른 위치나 디렉터리에서 실행될 때 제대로 작동하지 않습니다. Jenkins 에이전트.

이 게시물을 요약하면 다음과 같습니다.