View Javadoc

1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one
3    * or more contributor license agreements.  See the NOTICE file
4    * distributed with this work for additional information
5    * regarding copyright ownership.  The ASF licenses this file
6    * to you under the Apache License, Version 2.0 (the
7    * "License"); you may not use this file except in compliance
8    * with the License.  You may obtain a copy of the License at
9    *
10   *   http://www.apache.org/licenses/LICENSE-2.0
11   *
12   * Unless required by applicable law or agreed to in writing,
13   * software distributed under the License is distributed on an
14   * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15   * KIND, either express or implied.  See the License for the
16   * specific language governing permissions and limitations
17   * under the License.
18   */
19  package org.apache.myfaces.custom.exporter.util;
20  
21  import java.io.IOException;
22  import java.util.ArrayList;
23  import java.util.List;
24  
25  import javax.faces.component.UIColumn;
26  import javax.faces.component.UIComponent;
27  import javax.faces.component.ValueHolder;
28  import javax.faces.component.html.HtmlDataTable;
29  import javax.faces.context.FacesContext;
30  import javax.servlet.http.HttpServletResponse;
31  
32  import org.apache.myfaces.shared_tomahawk.renderkit.RendererUtils;
33  import org.apache.poi.hssf.usermodel.HSSFCell;
34  import org.apache.poi.hssf.usermodel.HSSFRow;
35  import org.apache.poi.hssf.usermodel.HSSFSheet;
36  import org.apache.poi.hssf.usermodel.HSSFWorkbook;
37  
38  /**
39   * This class is a utility class for serving excel exporting.
40   */
41  public class ExcelExporterUtil {
42      
43      private static void addColumnHeaders(HSSFSheet sheet, List columns) {
44          HSSFRow rowHeader = sheet.createRow(0);
45  
46          for (int i = 0; i < columns.size(); i++) {
47              UIColumn column = (UIColumn) columns.get(i);
48              addColumnValue(rowHeader, column.getHeader(), i);
49          }
50      }
51  
52      private static List getColumns(HtmlDataTable table) {
53          List columns = new ArrayList();
54          for (int i = 0; i < table.getChildCount(); i++) {
55              UIComponent child = (UIComponent) table.getChildren().get(i);
56              if (child instanceof UIColumn) {
57                  columns.add(child);
58              }
59          }
60          return columns;
61      }
62  
63      private static void addColumnValue(HSSFRow rowHeader,
64              UIComponent component, int index) {
65          HSSFCell cell = rowHeader.createCell((short) index);
66          cell.setEncoding(HSSFCell.ENCODING_UTF_16);
67          if (component instanceof ValueHolder) {
68              String stringValue = RendererUtils.getStringValue(FacesContext
69                      .getCurrentInstance(), component);
70              cell.setCellValue(stringValue);
71          }
72      }
73      
74      /*
75       * This method is used for adding the columns values to the HSSFSheet.
76       */
77      private static void generateTableContent(FacesContext facesContext,
78              HSSFSheet sheet, List columns, HtmlDataTable dataTable) {
79          
80          int numberOfColumns = columns.size();
81          int numberOfRows = dataTable.getRowCount();        
82          int startFrom = 0;
83          int currentIndex = 1;
84          int endAt = numberOfRows;         
85      
86          /* fill the table with the data. */
87          for (int i = startFrom; i < endAt; ++i) {
88              dataTable.setRowIndex(i);
89              HSSFRow row = sheet.createRow(currentIndex++);
90              for (int j = 0; j < numberOfColumns; ++j) {
91                  UIColumn column = (UIColumn) columns.get(j);
92                  addColumnValue(row, (UIComponent) column.getChildren().get(0),
93                          j);
94              }
95          }
96      }    
97      
98      /*
99       * This utility method is used for writing the excelModel (generatedExcel)
100      * to the response (response) and uses the (fileName) as the generated file 
101      * name.
102      */
103     private static void writeExcelToResponse(HttpServletResponse response,
104             HSSFWorkbook generatedExcel, String fileName) throws IOException {
105 
106         /* write the model to the stream */
107         response.setContentType("application/vnd.ms-excel");
108         response.setHeader("Expires", "0");
109         response.setHeader("Cache-Control",
110                 "must-revalidate, post-check=0, pre-check=0");
111         response.setHeader("Pragma", "public");
112         response.setHeader("Content-disposition", "attachment;filename="
113                 + fileName + ".xls");
114 
115         generatedExcel.write(response.getOutputStream());
116     }
117     
118     /*
119      * This utility method is used for generating the (HSSFWorkbook) 
120      * excel table model from the passed (HtmlDataTable).
121      * @param facesContext
122      * @param table the passed (HtmlDataTable).
123      * @return the (HSSFWorkbook) object. 
124      */
125     private static HSSFWorkbook generateExcelTableModel(
126             FacesContext facesContext, HtmlDataTable dataTable) {
127   
128         HSSFWorkbook workbook = new HSSFWorkbook();       
129         HSSFSheet sheet = workbook.createSheet(dataTable.getId());
130         List columns = getColumns(dataTable);
131         int currentRowIndex = dataTable.getRowIndex();
132 
133         addColumnHeaders(sheet, columns);
134         generateTableContent(facesContext, sheet, columns, dataTable);
135 
136         dataTable.setRowIndex(currentRowIndex);
137         return workbook;
138     }    
139 
140     /**
141      * This utility method is used for generating the excel 
142      * table to the HttpServletResponse object. 
143      * @param workBook
144      * @param response
145      * @param fileName
146      * @throws IOException
147      */    
148     public static void generateEXCEL(FacesContext facesContext,
149             HttpServletResponse response, String fileName, HtmlDataTable dataTable)
150             throws IOException {
151 
152         /*
153          * By default if the fileName is not specified, then use the
154          * table id.
155          */
156         if (fileName == null) 
157         {
158             fileName = dataTable.getId();
159         }
160 
161         /* generate the excel model */
162         HSSFWorkbook generatedExcel = ExcelExporterUtil
163                 .generateExcelTableModel(facesContext, dataTable);
164 
165         writeExcelToResponse(response, generatedExcel, fileName);
166     }
167 }