Reading excel file using primefaces and apache POI

Posted: February 19, 2013 in web

xhtml

 <h:form enctype="multipart/form-data">
 <p:fileUpload update="tt"
 sizeLimit="1000000"
 fileUploadListener="#{bBean.handleFileUpload}" mode="advanced"
 allowTypes="/(\.|\/)(xls)$/" />
 <p:growl id="tt" showDetail="true"/>
 </h:form>

web.xml

...
 <filter>
 <filter-name>PrimeFaces FileUpload Filter</filter-name>
 <filter-class>
 org.primefaces.webapp.filter.FileUploadFilter
 </filter-class>
 </filter>
 <filter-mapping>
 <filter-name>PrimeFaces FileUpload Filter</filter-name>
 <servlet-name>Faces Servlet</servlet-name>
 </filter-mapping>
...

Backing Bean

...
public void handleFileUpload(FileUploadEvent event) {
 if (event.getFile().equals(null)) {
 facesContext.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "File is null", null));
 }
 InputStream file;
 HSSFWorkbook workbook = null;
 try {
 file = event.getFile().getInputstream();
 workbook = new HSSFWorkbook(file);
 } catch (IOException e) {
 facesContext
 .addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Error reading file" + e, null));
 }

HSSFSheet sheet = workbook.getSheetAt(1);

Iterator<Row> rowIterator = sheet.iterator();
 Calendar calendar = new GregorianCalendar();
 while (rowIterator.hasNext()) {
 Row row = rowIterator.next();

Iterator<Cell> cellIterator = row.cellIterator();
 Job job = new Job();
 while (cellIterator.hasNext()) {
 Cell cell = cellIterator.next();

switch (cell.getCellType()) {
 case Cell.CELL_TYPE_NUMERIC:

if (HSSFDateUtil.isCellDateFormatted(cell) || HSSFDateUtil.isCellInternalDateFormatted(cell)) {
 calendar.setTime(cell.getDateCellValue());
 } else {
 System.out.print(cell.getNumericCellValue() + "\t\t");
 }
 break;
 case Cell.CELL_TYPE_STRING:
 System.out.print(cell.getStringCellValue() + "\t\t");
 break;
 }

}
 }
 }
...
Advertisements
Comments
  1. ocgalean says:

    just what I need, thanks for sharing!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s