Java Program to perform excel operations
In this article we will learn about Java program to perform excel operations. For QA, it is important to implement data provider using excel sheet in their automation framework and hence this article will come as a handy guide for the QA who are learning framework creation from scratch. we will try to cover all the excel methods and operations here.
Java program to perform excel operations
Firstly, you need to import POI jars in your workspace. then copy paste below code in your framework in a package called util.
package util;
import java.io.FileInputStream;
public class ExcelRead {
public static String filename = "" ;
private XSSFSheet worksheet = null;
private XSSFRow sheetRow = null;
public String path;
public FileInputStream fileInput = null;
public FileOutputStream fileOutput = null;
private XSSFWorkbook workbook = null;
private XSSFCell cell = null;
public ExcelRead(String path) { // Constructor declared
this.path =path;
try {
fileInput = new FileInpuutStream(path);
workbook = new XSSFWorkbook(fileInput);
worksheet = workbook.getSheetAt(0);
fileInput.close();
}
catch(Exception e) {
e.printStackTrace();
}
}
// return number of rows
public int fetchRowCount(String sheetName) {
int index = workbook.getSheetIndex(sheetName);
if(index == -1)
return 0;
else {
worksheet = workbook.getSheetAt(index);
int number = worksheet.getLastRowNum() + 1;
return number;
}
}
//return true if cell is updated
public boolean setCellValue(String sheetName, String colName, int rowNum, String data) {
try {
fileInput = new FileInputStream(path);
workbook = new XSSFWorkbook(fileInput);
if(rowNum <=0)
return false;
int index = workbook.getSheetIndex(sheetName);
int colNum = -1;
if(index = = -1)
return false;
workSheet = workBook.getSheetAt(index);
sheetRow = workSheet.getRow(0);
for(int i = 0;i< sheetRow.getLastCellNum(); i++ ) {
if(sheetRow.getCell(i).getStringCellValue().trim().equals(colName))
colNum = i;
}
if(colNum ==-1)
return false;
workSheet.autoSizeColumn(colNum);
sheetRow = workSheet.getRow(rowNum-1);
if(sheetRow == null)
sheetRow = workSheet.createRow(rowNum - 1);
cell = sheetRow.getCell(colNum);
if(cell == null)
cell = sheetRow.createCell(colNum);
}
//check whether work sheet exists or not
public boolean isSheetPresent(String sheetName) {
int index = workbook.getSheetIndex(sheetName);
if(index = = -1)
{
index = workbook.getSheetIndex(sheetName.toUpperCase());
if(index = = -1)
return false;
else
return true;
}
else
return true;
}
Comments
Post a Comment