KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > displaytag > render > HssfTableWriter


1 /**
2  * Licensed under the Artistic License; you may not use this file
3  * except in compliance with the License.
4  * You may obtain a copy of the License at
5  *
6  * http://displaytag.sourceforge.net/license.html
7  *
8  * THIS PACKAGE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR
9  * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
10  * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
11  */

12 package org.displaytag.render;
13
14 import java.util.Calendar JavaDoc;
15 import java.util.Date JavaDoc;
16 import java.util.Iterator JavaDoc;
17
18 import org.apache.commons.lang.ObjectUtils;
19 import org.apache.commons.lang.StringEscapeUtils;
20 import org.apache.commons.lang.StringUtils;
21 import org.apache.commons.lang.math.NumberUtils;
22 import org.apache.poi.hssf.usermodel.HSSFCell;
23 import org.apache.poi.hssf.usermodel.HSSFCellStyle;
24 import org.apache.poi.hssf.usermodel.HSSFDataFormat;
25 import org.apache.poi.hssf.usermodel.HSSFFont;
26 import org.apache.poi.hssf.usermodel.HSSFRow;
27 import org.apache.poi.hssf.usermodel.HSSFSheet;
28 import org.apache.poi.hssf.usermodel.HSSFWorkbook;
29 import org.apache.poi.hssf.util.HSSFColor;
30 import org.apache.poi.hssf.util.Region;
31 import org.displaytag.decorator.TableDecorator;
32 import org.displaytag.decorator.hssf.DecoratesHssf;
33 import org.displaytag.model.Column;
34 import org.displaytag.model.HeaderCell;
35 import org.displaytag.model.Row;
36 import org.displaytag.model.TableModel;
37
38
39 /**
40  * A table writer that formats a table in Excel's spreadsheet format, and writes it to an HSSF workbook.
41  * @author Jorge L. Barroso
42  * @version $Revision$ ($Author$)
43  * @see org.displaytag.render.TableWriterTemplate
44  */

45 public class HssfTableWriter extends TableWriterAdapter
46 {
47
48     /**
49      * The workbook to which the table is written.
50      */

51     private HSSFWorkbook wb;
52
53     /**
54      * Generated sheet.
55      */

56     private HSSFSheet sheet;
57
58     /**
59      * Current row number.
60      */

61     private int rowNum;
62
63     /**
64      * Current row.
65      */

66     private HSSFRow currentRow;
67
68     /**
69      * Current column number.
70      */

71     private int colNum;
72
73     /**
74      * Current cell.
75      */

76     private HSSFCell currentCell;
77
78     /**
79      * Percent Excel format.
80      */

81     private short pctFormat = HSSFDataFormat.getBuiltinFormat("0.00%");
82
83     /**
84      * This table writer uses an HSSF workbook to write the table.
85      * @param wb The HSSF workbook to write the table.
86      */

87     public HssfTableWriter(HSSFWorkbook wb)
88     {
89         this.wb = wb;
90     }
91
92     /**
93      * @see org.displaytag.render.TableWriterTemplate#writeTableOpener(org.displaytag.model.TableModel)
94      */

95     protected void writeTableOpener(TableModel model) throws Exception JavaDoc
96     {
97         this.sheet = wb.createSheet("-");
98         this.rowNum = 0;
99     }
100
101     /**
102      * @see org.displaytag.render.TableWriterTemplate#writeCaption(org.displaytag.model.TableModel)
103      */

104     protected void writeCaption(TableModel model) throws Exception JavaDoc
105     {
106         HSSFCellStyle style = this.wb.createCellStyle();
107         HSSFFont bold = this.wb.createFont();
108         bold.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
109         bold.setFontHeightInPoints((short) 14);
110         style.setFont(bold);
111         style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
112
113         this.colNum = 0;
114         this.currentRow = this.sheet.createRow(this.rowNum++);
115         this.currentCell = this.currentRow.createCell((short) this.colNum);
116         this.currentCell.setCellStyle(style);
117         String JavaDoc caption = model.getCaption();
118         this.currentCell.setCellValue(caption);
119         this.rowSpanTable(model);
120     }
121
122     /**
123      * Obtain the region over which to merge a cell.
124      * @param first Column number of first cell from which to merge.
125      * @param last Column number of last cell over which to merge.
126      * @return The region over which to merge a cell.
127      */

128     private Region getMergeCellsRegion(short first, short last)
129     {
130         return new Region(this.currentRow.getRowNum(), first, this.currentRow.getRowNum(), last);
131     }
132
133     /**
134      * @see org.displaytag.render.TableWriterTemplate#writeTableHeader(org.displaytag.model.TableModel)
135      */

136     protected void writeTableHeader(TableModel model) throws Exception JavaDoc
137     {
138         this.currentRow = this.sheet.createRow(this.rowNum++);
139         this.colNum = 0;
140         HSSFCellStyle headerStyle = this.getHeaderFooterStyle();
141         for (Iterator JavaDoc iterator = model.getHeaderCellList().iterator(); iterator.hasNext();)
142         {
143             HeaderCell headerCell = (HeaderCell) iterator.next();
144             String JavaDoc columnHeader = headerCell.getTitle();
145             if (columnHeader == null)
146             {
147                 columnHeader = StringUtils.capitalize(headerCell.getBeanPropertyName());
148             }
149
150             this.writeHeaderFooter(columnHeader, this.currentRow, headerStyle);
151         }
152     }
153
154     /**
155      * @see org.displaytag.render.TableWriterTemplate#writeDecoratedRowStart(org.displaytag.model.TableModel)
156      */

157     protected void writeDecoratedRowStart(TableModel model)
158     {
159         model.getTableDecorator().startRow();
160     }
161
162     /**
163      * @see org.displaytag.render.TableWriterTemplate#writeRowOpener(org.displaytag.model.TableModel)
164      */

165     protected void writeRowOpener(Row row) throws Exception JavaDoc
166     {
167         this.currentRow = this.sheet.createRow(rowNum++);
168         this.colNum = 0;
169     }
170
171     /**
172      * Write a column's opening structure to a HSSF document.
173      * @see org.displaytag.render.TableWriterTemplate#writeColumnOpener(org.displaytag.model.Column)
174      */

175     protected void writeColumnOpener(Column column) throws Exception JavaDoc
176     {
177         column.getOpenTag(); // has side effect, setting its stringValue, which affects grouping logic.
178
this.currentCell = this.currentRow.createCell((short) this.colNum++);
179         this.currentCell.setEncoding(HSSFCell.ENCODING_UTF_16);
180     }
181
182     /**
183      * @see org.displaytag.render.TableWriterTemplate#writeColumnValue(Object,org.displaytag.model.Column)
184      */

185     protected void writeColumnValue(Object JavaDoc value, Column column) throws Exception JavaDoc
186     {
187         if (value instanceof Number JavaDoc)
188         {
189             Number JavaDoc num = (Number JavaDoc) value;
190             // Percentage
191
if (value.toString().indexOf("%") > -1)
192             {
193                 this.currentCell.setCellValue(num.doubleValue() / 100);
194                 HSSFCellStyle cellStyle = this.wb.createCellStyle();
195                 cellStyle.setDataFormat(this.pctFormat);
196                 this.currentCell.setCellStyle(cellStyle);
197             }
198             else
199             {
200                 this.currentCell.setCellValue(num.doubleValue());
201             }
202         }
203         else if (value instanceof Date JavaDoc)
204         {
205             this.currentCell.setCellValue((Date JavaDoc) value);
206         }
207         else if (value instanceof Calendar JavaDoc)
208         {
209             this.currentCell.setCellValue((Calendar JavaDoc) value);
210         }
211         else
212         {
213             this.currentCell.setCellValue(this.escapeColumnValue(value));
214         }
215
216     }
217
218     /**
219      * @see org.displaytag.render.TableWriterTemplate#writeDecoratedRowFinish(org.displaytag.model.TableModel)
220      */

221     protected void writeDecoratedRowFinish(TableModel model) throws Exception JavaDoc
222     {
223         DecoratesHssf decorator = (DecoratesHssf) model.getTableDecorator();
224         decorator.setSheet(this.sheet);
225         ((TableDecorator) decorator).finishRow();
226         this.rowNum = this.sheet.getLastRowNum();
227         this.rowNum++;
228     }
229
230     /**
231      * @see org.displaytag.render.TableWriterTemplate#writePostBodyFooter(org.displaytag.model.TableModel)
232      */

233     protected void writePostBodyFooter(TableModel model) throws Exception JavaDoc
234     {
235         this.colNum = 0;
236         this.currentRow = this.sheet.createRow(this.rowNum++);
237         this.writeHeaderFooter(model.getFooter(), this.currentRow, this.getHeaderFooterStyle());
238         this.rowSpanTable(model);
239     }
240
241     /**
242      * Make a row span the width of the table.
243      * @param model The table model representing the rendered table.
244      */

245     private void rowSpanTable(TableModel model)
246     {
247         this.sheet.addMergedRegion(this.getMergeCellsRegion(this.currentCell.getCellNum(), (short) (model
248             .getNumberOfColumns() - 1)));
249     }
250
251     /**
252      * @see org.displaytag.render.TableWriterTemplate#writeDecoratedTableFinish(org.displaytag.model.TableModel)
253      */

254     protected void writeDecoratedTableFinish(TableModel model)
255     {
256         model.getTableDecorator().finish();
257     }
258
259     // patch from Karsten Voges
260
/**
261      * Escape certain values that are not permitted in excel cells.
262      * @param rawValue the object value
263      * @return the escaped value
264      */

265     protected String JavaDoc escapeColumnValue(Object JavaDoc rawValue)
266     {
267         if (rawValue == null)
268         {
269             return null;
270         }
271         String JavaDoc returnString = ObjectUtils.toString(rawValue);
272         // escape the String to get the tabs, returns, newline explicit as \t \r \n
273
returnString = StringEscapeUtils.escapeJava(StringUtils.trimToEmpty(returnString));
274         // remove tabs, insert four whitespaces instead
275
returnString = StringUtils.replace(StringUtils.trim(returnString), "\\t", " ");
276         // remove the return, only newline valid in excel
277
returnString = StringUtils.replace(StringUtils.trim(returnString), "\\r", " ");
278         // unescape so that \n gets back to newline
279
returnString = StringEscapeUtils.unescapeJava(returnString);
280         return returnString;
281     }
282
283     /**
284      * Is this value numeric? You should probably override this method to handle your locale.
285      * @param rawValue the object value
286      * @return true if numeric
287      */

288     protected boolean isNumber(String JavaDoc rawValue)
289     {
290         if (rawValue == null)
291         {
292             return false;
293         }
294         String JavaDoc rawV = rawValue;
295         if (rawV.indexOf('%') > -1)
296         {
297             rawV = rawV.replace('%', ' ').trim();
298         }
299         if (rawV.indexOf('$') > -1)
300         {
301             rawV = rawV.replace('$', ' ').trim();
302         }
303         if (rawV.indexOf(',') > -1)
304         {
305             rawV = StringUtils.replace(rawV, ",", "");
306         }
307         return NumberUtils.isNumber(rawV.trim());
308     }
309
310     /**
311      * Writes a table header or a footer.
312      * @param value Header or footer value to be rendered.
313      * @param row The row in which to write the header or footer.
314      * @param style Style used to render the header or footer.
315      */

316     private void writeHeaderFooter(String JavaDoc value, HSSFRow row, HSSFCellStyle style)
317     {
318         this.currentCell = row.createCell((short) this.colNum++);
319         this.currentCell.setCellValue(value);
320         this.currentCell.setCellStyle(style);
321         this.currentCell.setEncoding(HSSFCell.ENCODING_UTF_16);
322     }
323
324     /**
325      * Obtain the style used to render a header or footer.
326      * @return The style used to render a header or footer.
327      */

328     private HSSFCellStyle getHeaderFooterStyle()
329     {
330         HSSFCellStyle style = this.wb.createCellStyle();
331         style.setFillPattern(HSSFCellStyle.FINE_DOTS);
332         style.setFillBackgroundColor(HSSFColor.BLUE_GREY.index);
333         HSSFFont bold = this.wb.createFont();
334         bold.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
335         bold.setColor(HSSFColor.WHITE.index);
336         style.setFont(bold);
337         return style;
338     }
339 }
340
Popular Tags