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:

  • 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
  • Explain public static void main(String[] args){} public static void main(String[] args){} or public static void main(String... args){}: Java main method is the entry point of any java program. Its syntax is always "public static void main(String[] args)". You can only… 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
  • Fibonacci Series Write a Java Program to print Fibonacci  series up to 10        public class Fibonacci { public static void main(String[] args) { int num = 10;  … Read More
  • 2nd highest salary of an employee? MySQL: Sub queries in SQL are great tool for this kind of scenario, here we first select maximum salary and then another maximum excluding result of subquery mysql> SELECT max(salary) FROM Employee WHERE salary NOT IN (S… 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