File Handling | Reading data from Excel files (.xls or .xlsx) using JAVA.

Reading data from Excel files (.xls or .xlsx) using JAVA.

 

package excel;

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 
	{
		// TODO Auto-generated method stub
		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 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 cellIterator=rowIterator.next().cellIterator();
				while(cellIterator.hasNext())
				{
					String cellData=cellIterator.next().toString();
					System.out.print(cellData+"\t");
				}
				System.out.println();
			}
	}
	

}


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

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

1192total visits,2visits today

1 thought on “File Handling | Reading data from Excel files (.xls or .xlsx) using JAVA.”

  1. Thank you a lot for sharing this with all of us you really know what you’re speaking approximately! Bookmarked. Kindly also discuss with my web site =). We can have a hyperlink alternate contract among us!

Leave a Reply

Your email address will not be published. Required fields are marked *