December 21, 2010

Excel to Java Using POI libraries

My goal is to convert Excel data to Java Objects ( to our own POJOs).

There are two types of Excel versions:
1) Excel 97 - 2003 (*.xls ) and
2) Excel 2007 (*.xlsx) .

Libraries (jars) used are :
poi-3.6.jar for type 1,
poi-ooxml-3.6.jar for type 2.
These are from apache, we can download them from here

Code for 1st type:


try {
POIFSFileSystem fs = new POIFSFileSystem(new FileInputStream(fileNameWithPath)); // fileNameWithPath should be path to the '.xls' file.
HSSFWorkbook wb = new HSSFWorkbook(fs);
HSSFSheet sheet = wb.getSheetAt(0);
HSSFRow row = null;
if(sheet != null)
{
int first = sheet.getFirstRowNum();
int last = sheet.getLastRowNum();
first += 1; //Ignore first 1 row - they are headers
for(int i= first; i<=last; i++)
{
row = sheet.getRow(i);
if(row != null && row.getCell(COLUMN_CITY_NAME) != null)
{// COLUMN_CITY_NAME is an integer (actually starts with 0 )
/*code goes here to retrieve the cell information using row.getCell(colNum); */
}
}
}
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}


Code for 2nd Type:


try {
Workbook wb = new XSSFWorkbook(fileNameWithPath); // fileNameWithPath should be path to the '.xlsx' file.
Sheet sheet = wb.getSheetAt(0);
Row row;
if(sheet != null) {
int first = sheet.getFirstRowNum();
int last = sheet.getLastRowNum();
first += 1; //Ignore first 1 row - they are headers
for(int i= first; i<=last; i++)
{
row = sheet.getRow(i);
if(row != null && row.getCell(COLUMN_CITY_NAME) != null){
// COLUMN_CITY_NAME is an integer (actually starts with 0 )
/*code goes here to retrieve the cell information using
row.getCell(colNum);
*/
}
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

No comments:

Post a Comment