Tuesday, December 21, 2010

How to Read an Excel sheet using Apache POI HSSF

How to read an excel sheet using POI API(HSSF)

....
method to read the excel sheet and prepares the list(of Holiday DTOs) using apache POI API
.....

public static List parseHolidayExcel(String xlsPath) {

List holidayList = new ArrayList();
FileInputStream fis = null;
POIFSFileSystem fileSystem = null;

try {
fis = new FileInputStream(xlsPath);
fileSystem = new POIFSFileSystem(fis);

HSSFWorkbook workBook = new HSSFWorkbook(fileSystem);
HSSFSheet sheet = workBook.getSheetAt(0);
Iterator rows = sheet.rowIterator();
HolidayListDTO dto = null;
while (rows.hasNext()) {
HSSFRow row = rows.next();

if (row.getRowNum() == 0)
continue;

// System.out.println("Row no:"+row.getRowNum());
dto = new HolidayListDTO();
dto.setSiteStatus(row.getCell((short) 0).getStringCellValue());
dto.setCountry(row.getCell((short) 1).getStringCellValue());
dto.setLocation(row.getCell((short) 2).getStringCellValue());
dto.setHoliday_date((Date) (row.getCell((short) 3)
.getDateCellValue()));
dto.setDay(row.getCell((short) 4).getStringCellValue());
dto.setOccasion(row.getCell((short) 5).getStringCellValue());

holidayList.add(dto);

}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}

return holidayList;
}


To read an Excel sheet using POI API(HSSF) : Data Holder to hold details about the holidays....

import java.io.Serializable;
import java.util.Date;

public class HolidayListDTO implements Serializable{

public String siteStatus;
public String country;
public String location;
public Date holiday_date;
public String day;
public String occasion;
public String getSiteStatus() {
return siteStatus;
}
public void setSiteStatus(String siteStatus) {
this.siteStatus = siteStatus;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
public Date getHoliday_date() {
return holiday_date;
}
public void setHoliday_date(Date holidayDate) {
holiday_date = holidayDate;
}
public String getDay() {
return day;
}
public void setDay(String day) {
this.day = day;
}
public String getOccasion() {
return occasion;
}
public void setOccasion(String occasion) {
this.occasion = occasion;
}


}

Sample Excel file(sheet) to be read by the above code using POI HSSF API....

SiteStatus country location date day occasion
offsite india chennai 10/12/2010 Monday Ramzan
onsite us new jersy 11/12/2010 Tuesday Rangoli
offsite india delhi 9/11/2010 Wednesday deepavali

1 comment: