package poi;

import java.io.FileInputStream;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class ReadFromExcel {
	//Q: How to read from the existing excel sheet?
	public static void main(String[] args) {
		readFromExcel();
	}
	
	
	static void readFromExcel() {
		Workbook wb = null;
		Sheet sh = null;
		Row row = null;
		Cell cell = null;
		FileInputStream fin = null;
		String strData = null;
		int rowCount = 0;
		int colCount = 0;
		try {
			fin = new FileInputStream("C:\\MorningBatch_Combined\\Sample.xlsx");
			wb = new XSSFWorkbook(fin);  //Opening the existing excel file
			sh = wb.getSheet("testData");
			
			rowCount = sh.getPhysicalNumberOfRows();
			for(int r=0; r<rowCount; r++) {
				row = sh.getRow(r);
				
				colCount = row.getPhysicalNumberOfCells();
				
				for(int c=0; c<colCount; c++) {
					cell = row.getCell(c);
					strData = cell.getStringCellValue();
					System.out.print(strData + "    ");
				}
				System.out.println();
			}
		}catch(Exception e) {
			e.printStackTrace();
		}
		finally
		{
			try {
				fin.close();
				fin = null;
				cell = null;
				row = null;
				sh = null;
				wb.close();
				wb = null;
			}catch(Exception e) {
				e.printStackTrace();
			}
		}
	}
}
