Thursday, August 14, 2008

Reading From MS Excel using JAVA

The previous article has shown us how to write or populate the excel files. In this article, I walk through the steps of code of how to read from MS Excel file all using JAVA.


The steps for reading from MS Excel files are:
1. Opening the file with fileinputstream and opening the workbook of that excel file with the help of POI package.
2. Opening the HSSF sheet and HSSFcell to that row and column.
3. Get the value of that cell.



import java.io.FileInputStream;
import java.io.IOException;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

public class JavaExcelRead{
HSSFWorkbook workBook;
HSSFSheet sheet;
HSSFRow row;
HSSFCell cell;
FileInputStream fileInputStream;
HSSFWorkbook workbook;

JavaExcelRead(){
}

public void readFromExcelFile(){
double cellVal = 0.0;
// getting all the data from sheet
try{
FileInputStream fileInputStream = new FileInputStream("C:\\Demo.xls");
HSSFWorkbook workBook = new HSSFWorkbook(fileInputStream);
HSSFSheet sheet = workBook.getSheet("Demo");
HSSFRow row = sheet.getRow(0);
HSSFCell cell = null;
for(int i=0;i"lessthanequal"1;i++){
row = sheet.getRow(i);
for(int j=0;j"lessthanequal"1;j++){
cell = row.getCell((short)j);
System.out.println("Data is: "+cell.getStringCellValue());
}
}
fileInputStream.close();
}catch(IOException ioe){
ioe.printStackTrace();
}catch(Exception e){
e.printStackTrace();
}
}

public static void main(String args[]) {
JavaExcelRead jer = new JavaExcelRead();
jer.readFromExcelFile();
}
}

Hope you will find it useful.

No comments:

Total Pageviews