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.commons.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.poi.hssf.usermodel.HSSFCell;
33  import org.apache.poi.hssf.usermodel.HSSFRow;
34  import org.apache.poi.hssf.usermodel.HSSFSheet;
35  import org.apache.poi.hssf.usermodel.HSSFWorkbook;
36  
37  /**
38   * This class is a utility class for serving excel exporting.
39   */
40  public class ExcelExporterUtil 
41  {
42      
43      /**
44       * This utility method is used for generating the excel 
45       * table to the HttpServletResponse object. 
46       * @param workBook
47       * @param response
48       * @param fileName
49       * @throws IOException
50       */
51      public static void generateEXCEL(FacesContext facesContext,
52              HttpServletResponse response, String fileName,
53              HtmlDataTable dataTable) throws IOException
54      {
55  
56          /*
57           * By default if the fileName is not specified, then use the
58           * table id.
59           */
60          if (fileName == null)
61          {
62              fileName = dataTable.getId();
63          }
64  
65          /* generate the excel model */
66          HSSFWorkbook generatedExcel = ExcelExporterUtil
67                  .generateExcelTableModel(facesContext, dataTable);
68  
69          writeExcelToResponse(response, generatedExcel, fileName);
70      }    
71  
72      private static void addColumnHeaders(HSSFSheet sheet, List columns)
73      {
74          HSSFRow rowHeader = sheet.createRow(0);
75  
76          for (int i = 0; i < columns.size(); i++)
77          {
78              UIColumn column = (UIColumn) columns.get(i);
79              addColumnValue(rowHeader, column.getHeader(), i);
80          }
81      }
82  
83      private static List getColumns(HtmlDataTable table)
84      {
85          List columns = new ArrayList();
86          for (int i = 0; i < table.getChildCount(); i++)
87          {
88              UIComponent child = (UIComponent) table.getChildren().get(i);
89              if (child instanceof UIColumn)
90              {
91                  columns.add(child);
92              }
93          }
94          return columns;
95      }
96  
97      private static void addColumnValue(HSSFRow rowHeader,
98              UIComponent component, int index)
99      {
100         HSSFCell cell = rowHeader.createCell((short) index);
101         cell.setEncoding(HSSFCell.ENCODING_UTF_16);
102         if (component instanceof ValueHolder)
103         {
104             String stringValue = ComponentUtils.getStringValue(FacesContext
105                     .getCurrentInstance(), component);
106             cell.setCellValue(stringValue);
107         }
108     }
109 
110     private static void addColumnValue(HSSFRow rowHeader, String value,
111             int index)
112     {
113         HSSFCell cell = rowHeader.createCell((short) index);
114         cell.setEncoding(HSSFCell.ENCODING_UTF_16);
115         cell.setCellValue(value);
116     }
117 
118     /*
119      * This method is used for adding the columns values to the HSSFSheet.
120      */
121     private static void generateTableContent(FacesContext facesContext,
122             HSSFSheet sheet, List columns, HtmlDataTable dataTable)
123     {
124 
125         int numberOfColumns = columns.size();
126         int numberOfRows = dataTable.getRowCount();
127         int startFrom = 0;
128         int currentIndex = 1;
129         int endAt = numberOfRows;
130 
131         /* fill the table with the data. */
132         for (int i = startFrom; i < endAt; ++i)
133         {
134             dataTable.setRowIndex(i);
135             HSSFRow row = sheet.createRow(currentIndex++);
136             for (int j = 0; j < numberOfColumns; ++j)
137             {
138                 UIColumn column = (UIColumn) columns.get(j);
139                 String cellValue = "";
140 
141                 for (int k = 0; k < column.getChildren().size(); ++k)
142                 {
143                     if (column.getChildren().get(k) instanceof ValueHolder)
144                     {
145                         cellValue += ((ValueHolder) column.getChildren().get(k))
146                                 .getValue();
147                     }
148                 }
149                 addColumnValue(row, cellValue, j);
150             }
151         }
152     }
153 
154     /*
155      * This utility method is used for writing the excelModel (generatedExcel)
156      * to the response (response) and uses the (fileName) as the generated file
157      * name.
158      */
159     private static void writeExcelToResponse(HttpServletResponse response,
160             HSSFWorkbook generatedExcel, String fileName) throws IOException
161     {
162 
163         /* write the model to the stream */
164         response.setContentType("application/vnd.ms-excel");
165         response.setHeader("Expires", "0");
166         response.setHeader("Cache-Control",
167                 "must-revalidate, post-check=0, pre-check=0");
168         response.setHeader("Pragma", "public");
169         response.setHeader("Content-disposition", "attachment;filename="
170                 + fileName + ".xls");
171 
172         generatedExcel.write(response.getOutputStream());
173     }
174 
175     /*
176      * This utility method is used for generating the (HSSFWorkbook) 
177      * excel table model from the passed (HtmlDataTable).
178      * @param facesContext
179      * @param table the passed (HtmlDataTable).
180      * @return the (HSSFWorkbook) object. 
181      */
182     private static HSSFWorkbook generateExcelTableModel(
183             FacesContext facesContext, HtmlDataTable dataTable)
184     {
185 
186         HSSFWorkbook workbook = new HSSFWorkbook();
187         HSSFSheet sheet = workbook.createSheet(dataTable.getId());
188         List columns = getColumns(dataTable);
189         int currentRowIndex = dataTable.getRowIndex();
190 
191         addColumnHeaders(sheet, columns);
192         generateTableContent(facesContext, sheet, columns, dataTable);
193 
194         dataTable.setRowIndex(currentRowIndex);
195         return workbook;
196     }
197 }