Excel 파일에서 데이터를 읽고 쓰는 방법: Selenium POI
파일 IO는 모든 소프트웨어 프로세스에서 중요한 부분입니다. 우리는 컴퓨터에서 자주 파일을 생성하고, 열고, 업데이트하거나 삭제합니다. 의 경우도 마찬가지다 Selenium 오토메이션. 파일을 조작하는 프로세스가 필요합니다. Selenium.
Java 파일 조작을 위한 다양한 클래스를 제공합니다. Selenium. 이번 튜토리얼에서는 어떻게 읽고 쓰는지 배워보겠습니다. 뛰어나다 의 도움으로 파일 Java IO 패키지 및 아파치 POI 도서관.
아파치 POI Selenium
The 아파치 POI Selenium 셀레늄 데이터 기반 테스트를 위한 널리 사용되는 API입니다. POI 라이브러리로 작성되었습니다. Java 사용자에게 조작을 위한 API를 제공합니다. Microsoft .xls 및 .xlsx와 같은 문서. 사용자는 Excel 파일을 쉽게 생성, 수정하고 읽고 쓸 수 있습니다. POI는 "불량한 난독화 구현"을 의미합니다.
엑셀 내보내기
POI(Maven POM 종속성)를 사용하여 Excel 파일을 처리하는 방법
Excel 파일을 읽고 쓰려면 Java, Apache는 매우 유명한 라이브러리 POI를 제공합니다. 이 라이브러리는 두 가지 모두를 읽고 쓸 수 있을 만큼 충분합니다. XLS 그리고 XLSX 엑셀의 파일 형식.
읽다 XLS 파일, HSSF 구현은 POI 라이브러리에서 제공됩니다.
읽다 XLSX, XSSF 의 구현 POI 도서관 선택이 될 것입니다. 이러한 구현을 자세히 살펴보겠습니다.
프로젝트에서 Maven을 사용하는 경우 Maven 종속성은 다음과 같습니다.
<dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>4.1.1</version> </dependency>
또는 다음에서 최신 버전의 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 파일의 시트를 나타내는 클래스입니다.
- HSSF시트: XLS 파일의 시트를 나타내는 클래스입니다.
- 열: XSSFRow 및 HSSFrow 클래스가 이 인터페이스를 구현합니다.
- XSSF로우: XLSX 파일 시트의 행을 나타내는 클래스입니다.
- HSSF로우: XLS 파일 시트의 행을 나타내는 클래스입니다.
- 세포: XSSFCell 및 HSSFCell 클래스가 이 인터페이스를 구현합니다.
- XSSF셀: XLSX 파일의 행에 있는 셀을 나타내는 클래스입니다.
- HSSFC셀: XLS 파일 행의 셀을 나타내는 클래스입니다.
읽기/쓰기 작업
이 예에서는 아래 주어진 Excel 파일 형식을 고려합니다.
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");
}
}
참고: 우리는 테스트 중 여기에 프레임워크가 있습니다. 다음과 같이 수업을 실행하세요. Java Excel 읽기 기능을 사용하는 응용 프로그램 Selenium 위의 예에 표시된 것처럼.
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);
}
}
JXL API를 사용한 Excel 조작
JXL은 Excel 파일을 읽을 수 있는 또 다른 유명한 jar입니다. Java 그리고 파일 쓰기. 요즘은 대부분의 프로젝트에서 POI를 사용하지만 POI 이전에는 JXL만이 사용 가능했습니다. Java Excel 조작을 위한 API입니다. Excel 읽기를 위한 매우 작고 간단한 API입니다. Selenium.
팁: 내 제안은 라이브러리가 2010년부터 활발하게 개발되지 않고 POI API에 비해 기능이 부족하기 때문에 새 프로젝트에서는 JXL을 사용하지 않는 것입니다.
JXL 다운로드:
JXL로 작업하려면 이 링크에서 다운로드할 수 있습니다.
https://sourceforge.net/projects/jexcelapi/files/jexcelapi/2.6.12/
JXL용 압축 파일 내에서 데모 예제를 얻을 수도 있습니다.
일부 기능 :
- JXL은 Excel 파일을 읽을 수 있습니다. Selenium 95, 97, 2000, XP, 2003 통합 문서의 경우.
- 우리는 영어, 프랑스어, 스페인어, 독일어로 작업할 수 있습니다.
- 차트 복사 및 엑셀 이미지 삽입이 가능합니다.
약점:
- Excel 97 이상에서만 작성할 수 있습니다(Excel 95에서는 작성할 수 없습니다).
- JXL은 Excel 파일의 XLSX 형식을 지원하지 않습니다.
- Excel 2000 형식으로 스프레드시트를 생성합니다.
제품 개요
- Excel 파일을 읽을 수 있습니다. Java IO 작업. 이를 위해서는 다음을 사용해야 합니다. 아파치 POI 항아리.
- Excel 파일에는 두 가지 종류의 통합 문서가 있습니다. XLSX 그리고 XLS 파일.
- POI에는 통합 문서, 시트, 행, 셀 등 다양한 인터페이스가 있습니다.
- 이러한 인터페이스는 해당 인터페이스로 구현됩니다. XLS (HSSF워크북, HSSFSheet, HSSFRow, HSSFCell) and XLSX (XSSFWorkbook, XSSFSheet, XSSFrow, XSSFCell) 파일 조작 클래스.
- JXL은 Excel 처리를 위한 또 다른 API입니다. Selenium.
- JXL은 Excel의 XLSX 형식과 작동할 수 없습니다.









