We will see the use of apache POI library on excel read and write operations.
Download basic required apache POI jar files from here.
Add the below jar files along with selenium related to Eclipse:
poi-x.xx-*.jar (x-xx* for latest releases)
poi-ooxml-x.xx*.jar
xmlbeans-x.x.x.jar
poi-ooxml-schemas-x.xx-*.jar
Unlike jexcel api, apacke POI handles both the types of excel file, .xls and .xlsx file as well.
For handling .xls files, we use HSSF (Horrible SpreadSheet Format) related POI classes.
For handling .xlsx files, we use XSSF (XML SpreadSheet Format) related POI classes.
If you are using XSSF classes, then you can deal with both the excel format files, so no worries!
We will be only discussing the operations that are needed for our selenium framework and the operations are as listed below.
For handling .xls files, we use HSSF (Horrible SpreadSheet Format) related POI classes.
For handling .xlsx files, we use XSSF (XML SpreadSheet Format) related POI classes.
If you are using XSSF classes, then you can deal with both the excel format files, so no worries!
We will be only discussing the operations that are needed for our selenium framework and the operations are as listed below.
- Create an excel file if it's not existed.
- Enter (update) data in a cell.
- Read data from particular cell.
- Highlight particular cell.
package pkg.poi;
import java.awt.Color;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.DateUtil;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFColor;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class excelutil {
private static FileInputStream fis;
private static FileOutputStream fileOut;
private static XSSFWorkbook wb;
private static XSSFSheet sh;
private static XSSFCell cell;
private static XSSFRow row;
private static XSSFCellStyle cellstyle;
private static XSSFColor mycolor;
public static void setExcelFile(String ExcelPath,String SheetName) throws Exception
{
try{
File f = new File(ExcelPath);
if(!f.exists())
{
f.createNewFile();
System.out.println("File doesn't exist, so created!");
}
fis=new FileInputStream(ExcelPath);
wb=new XSSFWorkbook(fis);
sh = wb.getSheet(SheetName);
//sh = wb.getSheetAt(0); //0 - index of 1st sheet
if (sh == null)
{
sh = wb.createSheet(SheetName);
}
}catch (Exception e){System.out.println(e.getMessage());}
}
setExcelFile method takes 2 argument, path of excel file and sheet name, that we will be working on, we are checking if the excel file/sheet exist, if not, create it.
2) Enter(update) data in a cell
setCellData method takes 3 arguments, string text we want to enter into cell with rownum and colnum, this method enters data into an empty cell and also updates if data already existed.
public static void setCellData(String text, int rownum, int colnum) throws Exception
{
try{
row = sh.getRow(rownum);
if(row ==null)
{
row = sh.createRow(rownum);
}
cell = row.getCell(colnum);
if (cell != null)
{
cell.setCellValue(text);
}
else
{
cell = row.createCell(colnum);
cell.setCellValue(text);
}
fileOut = new FileOutputStream(ExcelPath);
wb.write(fileOut);
fileOut.flush();
fileOut.close();
}catch(Exception e){throw (e);} }
3) Read data from particular cell:
getCellData method takes the rownum and colnum to fetch the data from excel sheet,
excel path and sheet name are already taken care by the setExcelFile method.
There are different ways to fetch the data from cell, like we need to fetch the cell_type
1st and then fetch the data accordingly.
public static String getCellData(int rownum, int colnum) throws Exception
{
try{
cell = sh.getRow(rownum).getCell(colnum);
String CellData = null;
switch (cell.getCellType()){
case Cell.CELL_TYPE_STRING:
CellData = cell.getStringCellValue();
break;
case Cell.CELL_TYPE_NUMERIC:
if (DateUtil.isCellDateFormatted(cell))
{
CellData = cell.getDateCellValue().toString();
}
else
{
CellData = Double.toString(cell.getNumericCellValue());
if (CellData.contains(".0"))//removing the extra .0
{
CellData = CellData.substring(0, CellData.length()-2);
}
}
break;
case Cell.CELL_TYPE_BLANK:
CellData = "";
break;
case Cell.CELL_TYPE_BOOLEAN:
CellData = Boolean.toString(cell.getBooleanCellValue());
break;
}
return CellData;
}catch (Exception e){return"";}
}
4) Highlight particular cell.
highlightCell method takes 3 argument, which color to highlight the cell(row and col).
public static void highlightCell(String color, int rownum, int colnum)throws Exception
{
try{
cell = sh.getRow(rownum).getCell(colnum,Row.RETURN_BLANK_AS_NULL);
}catch(Exception e){System.out.println("cell is null");}
if (cell == null)
{
cell = row.createCell(colnum);
}
cellstyle = wb.createCellStyle();
color = color.toUpperCase();
switch(color)
{
case "GREEN":
mycolor = new XSSFColor(Color.GREEN);
break;
case "RED":
mycolor = new XSSFColor(Color.RED);
break;
default:
mycolor = new XSSFColor(Color.BLACK);
break;
}
cellstyle.setFillForegroundColor(mycolor);
cellstyle.setFillPattern(CellStyle.SOLID_FOREGROUND);
cell.setCellStyle(cellstyle);
FileOutputStream fileOut = new FileOutputStream(ExcelPath);
wb.write(fileOut);
fileOut.flush();
fileOut.close();
System.out.print("color done");
}
You can call the above 4 methods based on your requirement from the main() method of the same class or can import the class into another class(import pkg.poi.excelutil) and call these methods.
Let me know of any other requirements that needs to be added in this post, so everyone can leverage the code, Thanks!
Thank you for useful inoformation!
ReplyDeleteIot Training in Chennai
Big data Hadoop Training in chennai
This comment has been removed by the author.
ReplyDeleteHey, Your post is very informative and helpful for us.
ReplyDeleteIn fact i am looking this type of article from some days.
Thanks a lot to share this informative article.
Excel Training in Hyderabad
Thank you for taking the time to provide us with your valuable information. We strive to provide our candidates with excellent care and we take your comments to heart.As always, we appreciate your confidence and trust in us
ReplyDeletejava training in omr
java training in annanagar | java training in chennai
java training in marathahalli | java training in btm layout
java training in rajaji nagar | java training in jayanagar
Great Article… I love to read your articles because your writing style is too good, its is very very helpful for all of us and I never get bored while reading your article because, they are becomes a more and more interesting from the starting lines until the end.
ReplyDeletepython training in omr
python training in annanagar | python training in chennai
python training in marathahalli | python training in btm layout
python training in rajaji nagar | python training in jayanagar
I am a regular reader of your blog and being students it is great to read that your responsibilities have not prevented you from continuing your study and other activities. Love
ReplyDeleteData Science with Python training in chenni
Data Science training in chennai
Data science training in velachery
Data science training in tambaram
Data Science training in OMR
Data Science training in anna nagar
Data Science training in chennai
Data science training in Bangalore
Hmm, it seems like your site ate my first comment (it was extremely long) so I guess I’ll just sum it up what I had written and say, I’m thoroughly enjoying your blog. I as well as an aspiring blog writer, but I’m still new to the whole thing. Do you have any recommendations for newbie blog writers? I’d appreciate it.
ReplyDeleteBest Selenium Training in Chennai | Selenium Training Institute in Chennai | Besant Technologies
Selenium Training in Bangalore | Best Selenium Training in Bangalore
AWS Training in Bangalore | Amazon Web Services Training in Bangalore
I am glad that I came across your post. Looking forward to learn more.
ReplyDeleteRPA Training in Chennai
Blue Prism Training in Chennai
DevOps Training in Chennai
R Programming Training in Chennai
AWS Training in Chennai
DevOps Training in Chennai
Angularjs Training in Chennai
Data Science Course in Chennai
Very Clear Explanation. Thank you to share this
ReplyDeleteSelenium Training Institute in chennai | Selenium Testing Training in Chennai
Wow it is really wonderful and awesome thus it is very much useful for me to understand many concepts and helped me a lot. it is really explainable very well and i got more information from your blog.
ReplyDeletedevops online training
aws online training
data science with python online training
data science online training
rpa online training
Your good knowledge and kindness in playing with all the pieces were very useful. I don’t know what I would have done if I had not encountered such a step like this.
ReplyDeleteMicrosoft Azure online training
Selenium online training
Java online training
uipath online training
Python online training
This comment has been removed by the author.
ReplyDeleteGreat job.... Awesome list, just starting a blog and this is going to be a massive help. Thank you!
ReplyDeleteSoftware Testing Training in Chennai
Software Testing Training in Velachery
Software Testing Training in Tambaram
Software Testing Training in Porur
Software Testing Training in Omr
Software Testing Training in Annanagar
If you want a number of users to add information to your spreadsheet, you don't want them to leave out any relevant fields of information. custom excel spreadsheets
ReplyDeleteMmorpg
ReplyDeleteinstagram takipci satın al
tiktok jeton hilesi
tiktok jeton hilesi
antalya saç ekimi
instagram takipçi satın al
İnstagram Takipci Satın Al
metin2 pvp serverlar
Takipci Satın Al
SMM PANEL
ReplyDeleteSmm panel
iş ilanları
instagram takipçi satın al
https://www.hirdavatciburada.com
Beyazesyateknikservisi.com.tr
servis
tiktok jeton hilesi
üsküdar beko klima servisi
ReplyDeleteçekmeköy vestel klima servisi
ataşehir vestel klima servisi
çekmeköy bosch klima servisi
ataşehir bosch klima servisi
çekmeköy arçelik klima servisi
ataşehir arçelik klima servisi
kartal bosch klima servisi
kartal arçelik klima servisi
Success Write content success. Thanks.
ReplyDeletebetpark
deneme bonusu
kralbet
betmatik
canlı slot siteleri
betturkey
kıbrıs bahis siteleri
salt likit
ReplyDeletesalt likit
dr mood likit
big boss likit
dl likit
dark likit
CAY
bitlis
ReplyDeleteurfa
mardin
tokat
çorum
DYAV42
bartın evden eve nakliyat
ReplyDeleteedirne evden eve nakliyat
mersin evden eve nakliyat
sinop evden eve nakliyat
siirt evden eve nakliyat
MVAK
C58B7
ReplyDeletePancakeswap Güvenilir mi
Eskişehir Lojistik
Kırıkkale Evden Eve Nakliyat
Iğdır Lojistik
Bitexen Güvenilir mi
Uşak Şehir İçi Nakliyat
İzmir Şehir İçi Nakliyat
Silivri Duşa Kabin Tamiri
Bitrue Güvenilir mi
8BCF6
ReplyDeletereferanskodunedir.com.tr
AF1EC
ReplyDeleteKripto Para Madenciliği Siteleri
Binance Para Kazanma
Twitter Retweet Satın Al
Binance Referans Kodu
Sohbet
Binance Madenciliği Nedir
Bee Coin Hangi Borsada
Görüntülü Sohbet Parasız
Youtube Beğeni Hilesi
That was great to read. Keep it up with your writing skills.
ReplyDeleteJava Course in Pune