Como ler/gravar dados de arquivo Excel: Selenium POI
File IO รฉ uma parte crรญtica de qualquer processo de software. Freqรผentemente criamos um arquivo, abrimos e atualizamos algo ou excluรญmos em nossos computadores. O mesmo acontece com Selenium Automaรงรฃo. Precisamos de um processo para manipular arquivos com Selenium.
Java nos fornece diferentes classes para manipulaรงรฃo de arquivos com Selenium. Neste tutorial, aprenderemos como podemos ler e escrever em Excel arquivo com a ajuda de Java Pacote IO e apache Biblioteca de POIs.
Ponto de interesse do Apache em Selenium
O processo de Ponto de interesse do Apache em Selenium รฉ uma API amplamente usada para testes orientados a dados de selรชnio. ร uma biblioteca POI escrita em Java que fornece aos usuรกrios uma API para manipular Microsoft documentos como .xls e .xlsx. Os usuรกrios podem criar, modificar e ler/gravar facilmente em arquivos Excel. POI significa โImplementaรงรฃo de ofuscaรงรฃo deficienteโ.
Exportando Excel
Como lidar com arquivo Excel usando POI (Maven POM Dependency)
Para ler e gravar arquivos do Excel em Java, o Apache fornece uma biblioteca POI muito famosa. Esta biblioteca รฉ capaz o suficiente para ler e escrever ambos XLS e XLSX formato de arquivo do Excel.
Ler XLS arquivos, um HSSF a implementaรงรฃo รฉ fornecida pela biblioteca POI.
Ler XLSX, XSSFGenericName implementaรงรฃo de POI biblioteca serรก a escolha. Vamos estudar essas implementaรงรตes em detalhes.
Se vocรช estiver usando Maven em seu projeto, a dependรชncia do Maven serรก
<dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>4.1.1</version> </dependency>
Ou vocรช pode simplesmente baixar a versรฃo mais recente dos frascos de POI em http://poi.apache.org/download.html & baixe o arquivo zip mais recente
Ao baixar o arquivo zip deste jar, vocรช precisa descompactรก-lo e adicionar todos esses jars ao caminho de classe do seu projeto.
Classes e interfaces em POI

A seguir estรก uma lista de diferentes Java Interfaces e classes em POI para ler XLS e XLSX Arquivo-
- Livro. : As classes XSSFWorkbook e HSSFWorkbook implementam esta interface.
- Pasta de Trabalho XSSF: รฉ uma representaรงรฃo de classe do arquivo XLSX.
- Pasta de trabalho HSSF: รฉ uma representaรงรฃo de classe do arquivo XLS.
- seguranรงa: As classes XSSFSheet e HSSFSheet implementam esta interface.
- Folha XSSF: รฉ uma classe que representa uma planilha em um arquivo XLSX.
- Folha HSSF: รฉ uma classe que representa uma planilha em um arquivo XLS.
- Linha: As classes XSSFrow e HSSFrow implementam esta interface.
- XSFRow: รฉ uma classe que representa uma linha na planilha do arquivo XLSX.
- HSSFrow: รฉ uma classe que representa uma linha na planilha do arquivo XLS.
- Cรฉlula: As classes XSSFCell e HSSFCell implementam esta interface.
- Cรฉlula XSSF: รฉ uma classe que representa uma cรฉlula em uma linha do arquivo XLSX.
- Cรฉlula HSSF: ร uma classe que representa uma cรฉlula em uma linha do arquivo XLS.
Operaรงรฃo de leitura/gravaรงรฃo
Para nosso exemplo, consideraremos abaixo o formato de arquivo Excel fornecido
Ler dados do arquivo Excel
Exemplo completo: Aqui estamos tentando ler dados do Excel em 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");
}
}
Observaรงรฃo: nรฃo estamos usando o Teste quadro aqui. Execute a classe como Java Aplicativo usando funรงรฃo ler excel em Selenium como mostrado no exemplo acima.
Gravar dados em arquivo Excel
Exemplo completo: aqui estamos tentando gravar dados do arquivo Excel adicionando uma nova linha no arquivo 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);
}
}
Manipulaรงรฃo do Excel usando API JXL
JXL tambรฉm รฉ outro jar famoso para ler arquivos Excel Java e escrever arquivos. Hoje em dia o POI รฉ utilizado na maioria dos projetos, mas antes do POI o JXL era apenas Java API para manipulaรงรฃo do Excel. ร uma API muito pequena e simples para leitura do Excel em Selenium.
DICAS: Minha sugestรฃo รฉ nรฃo usar JXL em nenhum projeto novo porque a biblioteca nรฃo estรก em desenvolvimento ativo desde 2010 e falta do recurso em comparaรงรฃo com a API POI.
Baixe JXL:
Se quiser trabalhar com JXL, vocรช pode baixรก-lo neste link
https://sourceforge.net/projects/jexcelapi/files/jexcelapi/2.6.12/
Vocรช tambรฉm pode obter um exemplo de demonstraรงรฃo dentro deste arquivo compactado para JXL.
Alguns dos recursos:
- JXL รฉ capaz de ler arquivos Excel em Selenium para pasta de trabalho 95, 97, 2000, XP, 2003.
- Podemos trabalhar com inglรชs, francรชs, espanhol, alemรฃo.
- ร possรญvel copiar um grรกfico e inserir imagens no Excel
Recua:
- Podemos escrever apenas no Excel 97 e posterior (nรฃo hรก suporte para escrever no Excel 95).
- JXL nรฃo suporta o formato XLSX de arquivo Excel.
- Gera planilha no formato Excel 2000.
Resumo
- O arquivo Excel pode ser lido por Java Operaรงรฃo IO. Para isso, precisamos usar Jarro POI Apache.
- Existem dois tipos de pasta de trabalho no arquivo Excel, XLSX e XLS arquivos.
- POI tem diferentes interfaces de pasta de trabalho, planilha, linha, cรฉlula.
- Essas interfaces sรฃo implementadas por correspondentes XLS (HSSFWorkbook, HSSFSheet, HSSFrow, HSSFCell) e XLSX (XSSFWorkbook, XSSFSheet, XSSFrow, XSSFCell) classes de manipulaรงรฃo de arquivos.
- JXL รฉ outra API para manipulaรงรฃo do Excel em Selenium.
- JXL nรฃo pode funcionar com o formato XLSX do Excel.









