엑셀 데이터 읽기/쓰기 방법 Selenium Apache POI 사용
⚡ 스마트 요약
엑셀 파일 드라이브 Selenium 데이터 기반 테스트, 그리고 Apache POI는 바로 그것입니다. Java 이 라이브러리는 해당 파일을 읽고 쓰는 데 사용됩니다. 아래 섹션에서는 의존성, 핵심 클래스, 읽기 및 쓰기 예제, 그리고 JXL에 대해 설명합니다.
파일 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 아래 통합 문서에 대한 테스트입니다.
Excel 파일을 읽고 쓰려면 JavaApache는 매우 유명한 라이브러리인 POI를 제공합니다. 이 라이브러리는 Excel의 XLS 및 XLSX 파일 형식을 모두 읽고 쓸 수 있는 기능을 갖추고 있습니다.
XLS 파일을 읽기 위해 POI 라이브러리에서 HSSF 구현을 제공합니다.
XLSX 파일을 읽으려면 POI 라이브러리의 XSSF 구현체를 사용하는 것이 좋습니다. 이제 이러한 구현체들을 자세히 살펴보겠습니다.
프로젝트에서 Maven을 사용하는 경우, 아래와 같이 pom.xml 파일에 Maven 종속성이 추가됩니다.
<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 파일 다운로드
이 jar의 zip 파일을 다운로드할 때 압축을 풀고 이러한 모든 jar를 프로젝트의 클래스 경로에 추가해야 합니다.
POI의 클래스 및 인터페이스
다음은 다양한 목록입니다 Java POI에서 XLS 및 XLSX 파일을 읽기 위한 인터페이스와 클래스는 아래와 같습니다.
- 학습장: 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 파일에서 데이터 읽기
전체 예시: 여기서는 엑셀에서 데이터를 읽어오려고 합니다. 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 위의 예에 표시된 것처럼.
그러면 콘솔에 각 행이 셀 단위로 출력됩니다.
엑셀 파일에 데이터를 작성합니다
전체 예시: 여기서는 엑셀 파일에 새 행을 추가하여 데이터를 쓰는 방법을 시도하고 있습니다.
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); } }
그러면 통합 문서에는 추가된 행이 포함됩니다.
JXL API를 사용한 Excel 조작
JXL은 Excel 파일을 읽을 수 있는 또 다른 유명한 jar입니다. Java 그리고 파일 쓰기. 요즘은 대부분의 프로젝트에서 POI를 사용하지만 POI 이전에는 JXL만이 사용 가능했습니다. Java Excel 조작을 위한 API입니다. Excel 읽기를 위한 매우 작고 간단한 API입니다. Selenium.
도움말 : 제 생각에는 JXL은 2010년 이후로 활발한 개발이 중단되었고(최신 버전이 2.6.12입니다), POI API에 비해 기능이 부족하기 때문에 새로운 프로젝트에서는 사용하지 않는 것이 좋습니다.
JXL 다운로드:
JXL로 작업하려면 이 링크에서 다운로드할 수 있습니다.
https://sourceforge.net/projects/jexcelapi/files/jexcelapi/2.6.12/
이 압축 파일 안에는 JXL 데모 예제도 포함되어 있습니다.trac아래에 내용이 표시됩니다.
일부 기능 :
- JXL은 Excel 파일을 읽을 수 있습니다. Selenium 95, 97, 2000, XP, 2003 통합 문서의 경우.
- 우리는 영어, 프랑스어, 스페인어, 독일어로 작업할 수 있습니다.
- 차트 복사 및 엑셀 이미지 삽입이 가능합니다.
약점:
- Excel 97 이상에서만 작성할 수 있습니다(Excel 95에서는 작성할 수 없습니다).
- JXL은 Excel 파일의 XLSX 형식을 지원하지 않습니다.
- Excel 2000 형식으로 스프레드시트를 생성합니다.










