Thought of the Day!!!!!!!

Don't make EXCUSES, make IMPROVEMENTS. - Tyra Banks

Search This Blog

Saturday, August 19, 2017

How to read data from Excel files (.xls or .xlsx) using JAVA?

Question: How to read data from Excel files (.xls or .xlsx) using JAVA?

Code: 
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Iterator;
import org.apache.commons.io.FilenameUtils;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class ExcelHandling
{

public static void main(String[] args) throws IOException
{
String filePath="input_Excel//testData.xlsx";
loadFile(filePath);
}

public static void loadFile(String filePath) throws IOException
{
File file=new File(filePath);                                                     // Creating File Object
String fileExtension=FilenameUtils.getExtension(filePath);  // Getting extension of file
int totalRows=0;
Iterator<Row> rowIterator=null;

if(fileExtension.equalsIgnoreCase("xlsx"))
{
FileInputStream fis=new FileInputStream(file);
XSSFWorkbook doc =new XSSFWorkbook(fis);
XSSFSheet sheet=doc.getSheet("Sheet1");
        totalRows=sheet.getLastRowNum();
        rowIterator=sheet.rowIterator();
}
else if(fileExtension.equalsIgnoreCase("xls"))
{
FileInputStream fis =new FileInputStream(file);
HSSFWorkbook doc=new HSSFWorkbook(fis);
HSSFSheet sheet=doc.getSheet("Sheet1");
totalRows=sheet.getLastRowNum();
rowIterator=sheet.rowIterator();
}

System.out.println("Total Row Count : "+totalRows);
System.out.println("\nContent from document =>");
while(rowIterator.hasNext())
{
Iterator<Cell> cellIterator=rowIterator.next().cellIterator();
while(cellIterator.hasNext())
{
String cellData=cellIterator.next().toString();
System.out.print(cellData+"\t");
}
System.out.println();
}
}
}


Please do comment and share the post with your friends and colleagues. For any query or question, you can also email me at ashu.kumar940@gmail.com

Also, read How to read word document file using JAVA?

Other Blogs: 
https://agilehelpdoc.blogspot.in/

1 comment: