KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > displaytag > export > excel > ExcelHssfView


1 package org.displaytag.export.excel;
2
3 import java.io.OutputStream JavaDoc;
4 import java.util.Calendar JavaDoc;
5 import java.util.Date JavaDoc;
6 import java.util.Iterator JavaDoc;
7
8 import javax.servlet.jsp.JspException JavaDoc;
9
10 import org.apache.commons.lang.ObjectUtils;
11 import org.apache.commons.lang.StringEscapeUtils;
12 import org.apache.commons.lang.StringUtils;
13 import org.apache.poi.hssf.usermodel.HSSFCell;
14 import org.apache.poi.hssf.usermodel.HSSFCellStyle;
15 import org.apache.poi.hssf.usermodel.HSSFFont;
16 import org.apache.poi.hssf.usermodel.HSSFRow;
17 import org.apache.poi.hssf.usermodel.HSSFSheet;
18 import org.apache.poi.hssf.usermodel.HSSFWorkbook;
19 import org.apache.poi.hssf.util.HSSFColor;
20 import org.displaytag.Messages;
21 import org.displaytag.exception.BaseNestableJspTagException;
22 import org.displaytag.exception.SeverityEnum;
23 import org.displaytag.export.BinaryExportView;
24 import org.displaytag.model.Column;
25 import org.displaytag.model.ColumnIterator;
26 import org.displaytag.model.HeaderCell;
27 import org.displaytag.model.Row;
28 import org.displaytag.model.RowIterator;
29 import org.displaytag.model.TableModel;
30
31
32 /**
33  * Excel exporter using POI HSSF.
34  * @author Fabrizio Giustina
35  * @author rapruitt
36  * @version $Revision: 934 $ ($Author: fgiust $)
37  */

38 public class ExcelHssfView implements BinaryExportView
39 {
40
41     /**
42      * TableModel to render.
43      */

44     private TableModel model;
45
46     /**
47      * export full list?
48      */

49     private boolean exportFull;
50
51     /**
52      * include header in export?
53      */

54     private boolean header;
55
56     /**
57      * decorate export?
58      */

59     private boolean decorated;
60
61     /**
62      * Generated sheet.
63      */

64     private HSSFSheet sheet;
65
66     /**
67      * @see org.displaytag.export.ExportView#setParameters(TableModel, boolean, boolean, boolean)
68      */

69     public void setParameters(TableModel tableModel, boolean exportFullList, boolean includeHeader,
70         boolean decorateValues)
71     {
72         this.model = tableModel;
73         this.exportFull = exportFullList;
74         this.header = includeHeader;
75         this.decorated = decorateValues;
76     }
77
78     /**
79      * @return "application/vnd.ms-excel"
80      * @see org.displaytag.export.BaseExportView#getMimeType()
81      */

82     public String JavaDoc getMimeType()
83     {
84         return "application/vnd.ms-excel"; //$NON-NLS-1$
85
}
86
87     /**
88      * @see org.displaytag.export.BinaryExportView#doExport(OutputStream)
89      */

90     public void doExport(OutputStream JavaDoc out) throws JspException JavaDoc
91     {
92         try
93         {
94             HSSFWorkbook wb = new HSSFWorkbook();
95             sheet = wb.createSheet("-");
96
97             int rowNum = 0;
98             int colNum = 0;
99
100             if (this.header)
101             {
102                 // Create an header row
103
HSSFRow xlsRow = sheet.createRow(rowNum++);
104
105                 HSSFCellStyle headerStyle = wb.createCellStyle();
106                 headerStyle.setFillPattern(HSSFCellStyle.FINE_DOTS);
107                 headerStyle.setFillBackgroundColor(HSSFColor.BLUE_GREY.index);
108                 HSSFFont bold = wb.createFont();
109                 bold.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
110                 bold.setColor(HSSFColor.WHITE.index);
111                 headerStyle.setFont(bold);
112
113                 Iterator JavaDoc iterator = this.model.getHeaderCellList().iterator();
114
115                 while (iterator.hasNext())
116                 {
117                     HeaderCell headerCell = (HeaderCell) iterator.next();
118
119                     String JavaDoc columnHeader = headerCell.getTitle();
120
121                     if (columnHeader == null)
122                     {
123                         columnHeader = StringUtils.capitalize(headerCell.getBeanPropertyName());
124                     }
125
126                     HSSFCell cell = xlsRow.createCell((short) colNum++);
127                     cell.setCellValue(columnHeader);
128                     cell.setCellStyle(headerStyle);
129                     cell.setEncoding(HSSFCell.ENCODING_UTF_16);
130                 }
131             }
132
133             // get the correct iterator (full or partial list according to the exportFull field)
134
RowIterator rowIterator = this.model.getRowIterator(this.exportFull);
135             // iterator on rows
136

137             while (rowIterator.hasNext())
138             {
139                 Row row = rowIterator.next();
140                 HSSFRow xlsRow = sheet.createRow(rowNum++);
141                 colNum = 0;
142
143                 // iterator on columns
144
ColumnIterator columnIterator = row.getColumnIterator(this.model.getHeaderCellList());
145
146                 while (columnIterator.hasNext())
147                 {
148                     Column column = columnIterator.nextColumn();
149
150                     // Get the value to be displayed for the column
151
Object JavaDoc value = column.getValue(this.decorated);
152
153                     HSSFCell cell = xlsRow.createCell((short) colNum++);
154                     cell.setEncoding(HSSFCell.ENCODING_UTF_16);
155
156                     if (value instanceof Number JavaDoc)
157                     {
158                         Number JavaDoc num = (Number JavaDoc) value;
159                         cell.setCellValue(num.doubleValue());
160                     }
161                     else if (value instanceof Date JavaDoc)
162                     {
163                         cell.setCellValue((Date JavaDoc) value);
164                     }
165                     else if (value instanceof Calendar JavaDoc)
166                     {
167                         cell.setCellValue((Calendar JavaDoc) value);
168                     }
169                     else
170                     {
171                         cell.setCellValue(escapeColumnValue(value));
172                     }
173
174                 }
175             }
176             wb.write(out);
177         }
178         catch (Exception JavaDoc e)
179         {
180             throw new ExcelGenerationException(e);
181         }
182     }
183
184     // patch from Karsten Voges
185
/**
186      * Escape certain values that are not permitted in excel cells.
187      * @param rawValue the object value
188      * @return the escaped value
189      */

190     protected String JavaDoc escapeColumnValue(Object JavaDoc rawValue)
191     {
192         if (rawValue == null)
193         {
194             return null;
195         }
196         String JavaDoc returnString = ObjectUtils.toString(rawValue);
197         // escape the String to get the tabs, returns, newline explicit as \t \r \n
198
returnString = StringEscapeUtils.escapeJava(StringUtils.trimToEmpty(returnString));
199         // remove tabs, insert four whitespaces instead
200
returnString = StringUtils.replace(StringUtils.trim(returnString), "\\t", " ");
201         // remove the return, only newline valid in excel
202
returnString = StringUtils.replace(StringUtils.trim(returnString), "\\r", " ");
203         // unescape so that \n gets back to newline
204
returnString = StringEscapeUtils.unescapeJava(returnString);
205         return returnString;
206     }
207
208     /**
209      * Wraps IText-generated exceptions.
210      * @author Fabrizio Giustina
211      * @version $Revision: 934 $ ($Author: fgiust $)
212      */

213     static class ExcelGenerationException extends BaseNestableJspTagException
214     {
215
216         /**
217          * D1597A17A6.
218          */

219         private static final long serialVersionUID = 899149338534L;
220
221         /**
222          * Instantiate a new PdfGenerationException with a fixed message and the given cause.
223          * @param cause Previous exception
224          */

225         public ExcelGenerationException(Throwable JavaDoc cause)
226         {
227             super(ExcelHssfView.class, Messages.getString("ExcelView.errorexporting"), cause); //$NON-NLS-1$
228
}
229
230         /**
231          * @see org.displaytag.exception.BaseNestableJspTagException#getSeverity()
232          */

233         public SeverityEnum getSeverity()
234         {
235             return SeverityEnum.ERROR;
236         }
237     }
238
239 }
240
Popular Tags