Selenium support only browser automation so for reading and writing with Excel files we have to user third party API like JExcel and Apache POI.
here we are using JExcel
For this, we have to download jxl.jar file. For downloading this jar file search on google for “download jxl.jar file” or click on below link
download the zip file. extract the same.
Now Add the jxl.jar file to project.
Right Click on project then Click on Build path> then Click on configure build path then Go to Library Section then
Click on add external jars and now attach jar file click on Apply finally click on Save button.
Click on add external jars and now attach jar file click on Apply finally click on Save button.
And Here is the Code.
package TEST;
import jxl.*;
import jxl.read.biff.BiffException;
import jxl.write.*;
import jxl.read.biff.BiffException;
import jxl.write.*;
import java.io.File;
import java.io.IOException;
import java.io.IOException;
public class readExcelFile {
public static void main(String[] args) throws WriteException {
try {
//define workbook
Workbook wb = null;
try {
//initialize work book to read
wb = Workbook.getWorkbook(new File(“D:\\Ashu\\Selenium\\testJexcel.xls”));
} catch (BiffException e) {
e.printStackTrace();
}
//get first sheet
Sheet sh = wb.getSheet(0);
public static void main(String[] args) throws WriteException {
try {
//define workbook
Workbook wb = null;
try {
//initialize work book to read
wb = Workbook.getWorkbook(new File(“D:\\Ashu\\Selenium\\testJexcel.xls”));
} catch (BiffException e) {
e.printStackTrace();
}
//get first sheet
Sheet sh = wb.getSheet(0);
//print first sheet name
String sheetName=sh.getName();
String sheetName=sh.getName();
System.out.println(“Sheet name :”+sheetName);
//define cell string or number variable
String cellString = null;
double cellNumber = 0;
String cellString = null;
double cellNumber = 0;
//loop through each cell and read content
//you can give here the your excel sheets row and col value in for loop for condition.
for(int row=0;row<4;row++) {
for (int col = 0; col < 3; col++) {
Cell cell = sh.getCell(col, row);
if (cell.getType() == CellType.LABEL) {
cellString = cell.getContents();
System.out.print(cellString +” “);
} else if (cell.getType() == CellType.NUMBER) {
NumberCell nc = (NumberCell) cell;
cellNumber = nc.getValue();
//System.out.print(cellNumber + ” ,”);
}
Cell cell = sh.getCell(col, row);
if (cell.getType() == CellType.LABEL) {
cellString = cell.getContents();
System.out.print(cellString +” “);
} else if (cell.getType() == CellType.NUMBER) {
NumberCell nc = (NumberCell) cell;
cellNumber = nc.getValue();
//System.out.print(cellNumber + ” ,”);
}
}
//start new line for new row
System.out.println();
}
//close work book
wb.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
//start new line for new row
System.out.println();
}
//close work book
wb.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
very helpful ty
ReplyDeletethanks
Deletethanks
ReplyDelete