Thursday, March 4, 2010

How to read Excel file in Java

1. you need to download org.apache.poi from:
http://poi.apache.org/download.html

2. then you can use the package just downloaded in Java, and of course you need to put the package in your own project

3. The following code showing you the simple procedure to read an Excel file:

//http://poi.apache.org/index.html
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;

class sample
{
void readExcelFile(String excelFileName)
{
try
{
POIFSFileSystem fs = new POIFSFileSystem(new FileInputStream(excelFileName));
HSSFWorkbook wb = new HSSFWorkbook(fs);
HSSFSheet sheet = wb.getSheetAt(0);
HSSFRow row = null;
HSSFCell cell = null;

int count_rows; // NO of rows
count_rows = sheet.getPhysicalNumberOfRows();

int count_columns = 0; // NO of columns
int current_columns = 0;

// This trick ensures that we get the data properly even if it
// doesn't start from first few rows
for (int r = 0; r<10 && r < count_rows; r++)
{
row = sheet.getRow(r);
if (row != null)
{
current_columns = row.getPhysicalNumberOfCells();
if (current_columns > count_columns)
count_columns = current_columns;
}
}

for (int r = 0; r < count_rows; r++)
{
row = sheet.getRow(r);
if (row != null)
{// process one row
for (int c = 0; c < count_columns; c++)
{
cell = row.getCell(c);
if (cell != null)
{// main part of processing cells

System.out.print(cell.getStringCellValue()+" ");
}
}
System.out.println();
}
}
}
catch (Exception ioe)
{
ioe.printStackTrace();
}
}
}

No comments: