Monday, December 31, 2018

A Java Program to retrieve the data from an excel file?
  Below is the code to read .xlsx file.
                               XSSFWorkbook -> to read .xlsx file (Microsoft Excel 2003 and earlier)
                               HSSFWorkbook -> to read .xls file (Microsoft Excel 2007 and later)
   Ans: We can read  data from Excel using Apache POI library.

   public class ExcelDataRead {
public static void main(String[] args) {
try{
InputStream file=new FileInputStream("C:\\Users\\user\\Documents\\testdata.xlsx");
XSSFWorkbook workbook=new XSSFWorkbook(file);
XSSFSheet sheet=workbook.getSheet("Sheet1");
Iterator<Row> rows=sheet.rowIterator();
while(rows.hasNext()) {
XSSFRow row = (XSSFRow)rows.next();
Iterator<Cell> cells=row.cellIterator();
while(cells.hasNext()) {
XSSFCell cell=(XSSFCell)cells.next();
if(cell.getCellType()==CellType.STRING) {
System.out.print(cell.getStringCellValue());
}else if(cell.getCellType()==CellType.NUMERIC){
System.out.print(cell.getNumericCellValue());
}
}
}
workbook.close();
file.close();
} catch (IOException e) {
e.printStackTrace();

}
      }

NOTE: if you are using version  greater than 3.15v then replace CellType.STRING with XSSFCell.CELL_TYPE_STRING

Related Posts:

  • Static Keyword Static is a keyword in Java, which is used for static blocks variables methods and  inner classes or nested classes A static member can be accessed directly with the class name with out creating an object.  Th… Read More
  • TestNG Annotations What is TesNG and What are the annotations in the TestNG?      Ans: TestNG is testing framework to run the test cases. TestNG supports annotations like:       @BeforeSuite       &… Read More
  • foreach() method in Java Java API provides foreach() method since jdk1.8v. This method traverses each element of the collection until all elements have been Processed by the method or an exception is raised. Exceptions thrown by the Operation are pa… Read More
  • HashMap vs ConcurrentHashMap Difference between HashMap and ConcurrentHashMap: ConcurrentHashMap is thread-safe that is the code can be accessed by single thread at a time. while HashMap is not thread-safe HashMap can be synchronized by using sy… Read More
  • String Reverse Example public class StringReverse { public static void main(String[] args) { String str="selenium",reverse=""; for(int i=str.length()-1;i>=0;i--) { reverse=reverse+str.charAt(i… Read More

0 comments:

Post a Comment

Selenium Training in Realtime

Blog helps to a student or IT employee to develop or improve skills in Software Testing.

Followers

About Me

My photo
Hyderabad, Andhra Pradesh, India
I am Automation Testing Professional. I have completed my graduation in B.Tech (Computers) from JNTU Hyderabad and started my career in Software Testing accidentally since then, I passionate on learning new technologies

Contact Form

Name

Email *

Message *

Popular Posts