KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > cocoon > generation > HSSFGenerator


1 /*
2  * Copyright 2004-2005 The Apache Software Foundation.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */

16 package org.apache.cocoon.generation;
17
18 import org.apache.avalon.framework.configuration.Configurable;
19 import org.apache.avalon.framework.configuration.Configuration;
20 import org.apache.avalon.framework.configuration.ConfigurationException;
21 import org.apache.avalon.framework.parameters.Parameters;
22
23 import org.apache.cocoon.ProcessingException;
24 import org.apache.cocoon.components.source.SourceUtil;
25 import org.apache.cocoon.environment.SourceResolver;
26 import org.apache.commons.lang.BooleanUtils;
27
28 import org.apache.excalibur.source.Source;
29 import org.apache.excalibur.source.SourceException;
30 import org.apache.poi.hssf.usermodel.HSSFCell;
31 import org.apache.poi.hssf.usermodel.HSSFCellStyle;
32 import org.apache.poi.hssf.usermodel.HSSFFont;
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 import org.xml.sax.SAXException JavaDoc;
37 import org.xml.sax.helpers.AttributesImpl JavaDoc;
38
39 import java.io.IOException JavaDoc;
40 import java.util.Iterator JavaDoc;
41 import java.util.Map JavaDoc;
42
43 /**
44  * This generator generates - using Apache POI - a Gnumeric compliant XML
45  * Document from a Microsoft Excel Workbook.
46  *
47  * <h3>Sitemap Definition</h3>
48  * &lt;map:generator type="xls" SRC="org.apache.cocoon.generation.HSSFGenerator"&gt;
49  * &lt;uri&gt;http://www.gnome.org/gnumeric/v7&lt;/uri&gt;
50  * &lt;prefix&gt;gmr&lt;/prefix&gt;
51  * &lt;formatting&gt;false&lt;/formatting&gt;
52  * &lt;/map:generator&gt;
53  *
54  * <h3>Sitemap Use</h3>
55  * &lt;map:generate type="xls" SRC="spreadsheet.xls"/&gt;
56  *
57  * <p>You can set the parameter <code>formatting</code> to <code>true</code>
58  * in order to receive not only the data but also the formatting information
59  * of the workbook.</p>
60  *
61  * @author <a HREF="patrick@arpage.ch">Patrick Herber</a>
62  * @version $Id: HSSFGenerator.java 227036 2005-08-02 16:46:38Z cziegeler $
63  */

64 public class HSSFGenerator extends AbstractGenerator
65                            implements Configurable {
66
67     public static final String JavaDoc NAMESPACE_PREFIX = "gmr";
68     public static final String JavaDoc NAMESPACE_URI = "http://www.gnome.org/gnumeric/v7";
69     private static final boolean FORMATTING = false;
70
71     private static final String JavaDoc CONF_NAMESPACE_URI = "uri";
72     private static final String JavaDoc CONF_NAMESPACE_PREFIX = "prefix";
73     private static final String JavaDoc CONF_FORMATTING = "formatting";
74
75     private String JavaDoc defaultUri;
76     private String JavaDoc defaultPrefix;
77     private boolean defaultFormatting;
78
79     private String JavaDoc uri;
80     private String JavaDoc prefix;
81     private boolean formatting;
82     private final AttributesImpl JavaDoc attr;
83
84     protected Source inputSource;
85
86
87     public HSSFGenerator() {
88         this.attr = new AttributesImpl JavaDoc();
89     }
90
91     public void configure(Configuration configuration) throws ConfigurationException {
92         this.defaultUri = configuration.getChild(CONF_NAMESPACE_URI).getValue(NAMESPACE_URI);
93         this.defaultPrefix = configuration.getChild(CONF_NAMESPACE_PREFIX).getValue(NAMESPACE_PREFIX);
94         this.defaultFormatting = configuration.getChild(CONF_FORMATTING).getValueAsBoolean(FORMATTING);
95     }
96
97     public void setup(SourceResolver resolver, Map JavaDoc objectModel, String JavaDoc src, Parameters par)
98     throws ProcessingException, SAXException JavaDoc, IOException JavaDoc {
99         super.setup(resolver, objectModel, src, par);
100         this.uri = par.getParameter(CONF_NAMESPACE_URI, this.defaultUri);
101         this.prefix = par.getParameter(CONF_NAMESPACE_PREFIX, this.defaultPrefix);
102         this.formatting = par.getParameterAsBoolean(CONF_FORMATTING, this.defaultFormatting);
103
104         try {
105             this.inputSource = super.resolver.resolveURI(src);
106         } catch (SourceException se) {
107             throw SourceUtil.handle("Error resolving '" + src + "'.", se);
108         }
109     }
110
111     /**
112      * Recycle this component. All instance variables are set to
113      * <code>null</code>.
114      */

115     public void recycle() {
116         if (this.inputSource != null) {
117             super.resolver.release(this.inputSource);
118             this.inputSource = null;
119         }
120         this.attr.clear();
121         super.recycle();
122     }
123
124     /**
125      * Generate XML data.
126      */

127     public void generate() throws SAXException JavaDoc, IOException JavaDoc {
128         HSSFWorkbook workbook =
129                 new HSSFWorkbook(this.inputSource.getInputStream());
130         writeXML(workbook);
131     }
132
133
134     /**
135      * Writes out the workbook data as XML, without formatting information
136      */

137     private void writeXML(HSSFWorkbook workbook) throws SAXException JavaDoc {
138         this.contentHandler.startDocument();
139         start("Workbook");
140         start("SheetNameIndex");
141         for (int i = 0; i < workbook.getNumberOfSheets(); i++) {
142             start("SheetName");
143             data(workbook.getSheetName(i));
144             end("SheetName");
145         }
146         end("SheetNameIndex");
147         start("Sheets");
148         for (int i = 0; i < workbook.getNumberOfSheets(); i++) {
149             HSSFSheet sheet = workbook.getSheetAt(i);
150             start("Sheet");
151             start("Name");
152             data(workbook.getSheetName(i));
153             end("Name");
154             start("MaxCol");
155             data(Integer.toString(getMaxCol(sheet)));
156             end("MaxCol");
157             start("MaxRow");
158             data(Integer.toString(sheet.getLastRowNum()));
159             end("MaxRow");
160             if (formatting) {
161                 writeStyles(workbook, sheet);
162             }
163
164             start("Cells");
165             final Iterator JavaDoc rows = sheet.rowIterator();
166             while (rows.hasNext()) {
167                 final HSSFRow row = (HSSFRow) rows.next();
168                 final Iterator JavaDoc cells = row.cellIterator();
169                 while (cells.hasNext()) {
170                     final HSSFCell cell = (HSSFCell) cells.next();
171                     attribute("Row", Integer.toString(row.getRowNum()));
172                     attribute("Col", Short.toString(cell.getCellNum()));
173                     attribute("ValueType", getValueType(cell.getCellType()));
174                     start("Cell");
175                     data(getValue(cell));
176                     end("Cell");
177                 }
178             }
179             end("Cells");
180
181             end("Sheet");
182         }
183         end("Sheets");
184         end("Workbook");
185         this.contentHandler.endDocument();
186     }
187
188     /**
189      * Returns the max column index of the given sheet
190      * @param sheet
191      * @return the max column index
192      */

193     private int getMaxCol(HSSFSheet sheet) {
194         int max = -1;
195         HSSFRow row = null;
196         Iterator JavaDoc rows = sheet.rowIterator();
197         while (rows.hasNext()) {
198             row = (HSSFRow) rows.next();
199             int lastNum = row.getLastCellNum();
200             if (lastNum > max) {
201                 max = lastNum;
202             }
203         }
204         return max;
205     }
206
207     /**
208      * Returns the Gnumeric cell type.
209      * @param cellType POI cell type
210      * @return the Gnumeric cell type.
211      */

212     private String JavaDoc getValueType(int cellType) {
213         switch (cellType) {
214             case HSSFCell.CELL_TYPE_BLANK:
215                 return "10";
216             case HSSFCell.CELL_TYPE_BOOLEAN:
217                 return "20";
218             case HSSFCell.CELL_TYPE_NUMERIC:
219                 return "40";
220             case HSSFCell.CELL_TYPE_ERROR:
221                 return "50";
222             case HSSFCell.CELL_TYPE_FORMULA:
223             case HSSFCell.CELL_TYPE_STRING:
224             default:
225                 return "60";
226         }
227     }
228
229     /**
230      * Returns the cell value.
231      * @param cell POI cell
232      * @return the cell value
233      */

234     private String JavaDoc getValue(HSSFCell cell) {
235         switch (cell.getCellType()) {
236             case HSSFCell.CELL_TYPE_BLANK:
237                 return "";
238             case HSSFCell.CELL_TYPE_BOOLEAN:
239                 return BooleanUtils.toStringTrueFalse(cell.getBooleanCellValue());
240             case HSSFCell.CELL_TYPE_NUMERIC:
241                 return Double.toString(cell.getNumericCellValue());
242             case HSSFCell.CELL_TYPE_ERROR:
243                 return "#ERR" + cell.getErrorCellValue();
244             case HSSFCell.CELL_TYPE_FORMULA:
245             case HSSFCell.CELL_TYPE_STRING:
246             default:
247                 return cell.getStringCellValue();
248         }
249     }
250
251     /**
252      * Writes out the workbook data as XML, with formatting information
253      */

254     private void writeStyles(HSSFWorkbook workbook, HSSFSheet sheet)
255     throws SAXException JavaDoc {
256         start("Styles");
257         HSSFRow row = null;
258         HSSFCell cell = null;
259         Iterator JavaDoc cells = null;
260         Iterator JavaDoc rows = sheet.rowIterator();
261         while (rows.hasNext()) {
262             row = (HSSFRow) rows.next();
263             cells = row.cellIterator();
264             while (cells.hasNext()) {
265                 cell = (HSSFCell) cells.next();
266                 attribute("startRow", Integer.toString(row.getRowNum()));
267                 attribute("endRow", Integer.toString(row.getRowNum()));
268                 attribute("startCol", Short.toString(cell.getCellNum()));
269                 attribute("endCol", Short.toString(cell.getCellNum()));
270                 start("StyleRegion");
271                 HSSFCellStyle style = cell.getCellStyle();
272                 attribute("HAlign", Integer.toString(style.getAlignment()));
273                 attribute("VAlign", Integer.toString(style.getVerticalAlignment()));
274                 attribute("WrapText", ((style.getWrapText()) ? "1" : "0"));
275                 attribute("Orient", Integer.toString(style.getRotation()));
276                 attribute("Indent", Integer.toString(style.getIndention()));
277                 attribute("Locked", ((style.getLocked()) ? "1" : "0"));
278                 attribute("Hidden", ((style.getHidden()) ? "1" : "0"));
279                 attribute("Fore", workbook.getCustomPalette().getColor(style.getFillForegroundColor()).getHexString());
280                 attribute("Back", workbook.getCustomPalette().getColor(style.getFillBackgroundColor()).getHexString());
281                 attribute("PatternColor", Integer.toString(style.getFillPattern())); // TODO
282
attribute("Format", "General"); // TODO
283
start("Style");
284                 HSSFFont font = workbook.getFontAt(style.getFontIndex());
285                 attribute("Unit", Short.toString(font.getFontHeightInPoints()));
286                 attribute("Bold", Short.toString(font.getBoldweight()));
287                 attribute("Italic", ((font.getItalic()) ? "1" : "0"));
288                 attribute("Unterline", Integer.toString(font.getUnderline()));
289                 attribute("StrikeThrough", ((font.getStrikeout()) ? "1" : "0"));
290                 start("Font");
291                 data(font.getFontName());
292                 end("Font");
293                 end("Style");
294                 end("StyleRegion");
295             }
296         }
297         end("Styles");
298     }
299
300     //
301
// Utility methods
302
//
303

304     /**
305      * Adds an attribute with the given name and value.
306      */

307     private void attribute(String JavaDoc name, String JavaDoc value) {
308         attr.addAttribute("", name, name, "CDATA", value);
309     }
310
311     /**
312      * Starts an element with the given local name.
313      * @param name local name of the element
314      * @throws SAXException
315      */

316     private void start(String JavaDoc name) throws SAXException JavaDoc {
317         super.contentHandler.startElement(uri, name, prefix + ":" + name, attr);
318         attr.clear();
319     }
320
321     /**
322      * Ends the given element.
323      * @param name local name of the element
324      * @throws SAXException
325      */

326     private void end(String JavaDoc name) throws SAXException JavaDoc {
327         super.contentHandler.endElement(uri, name, prefix + ":" + name);
328     }
329
330     /**
331      * Writes the given element data.
332      * @param data
333      * @throws SAXException
334      */

335     private void data(String JavaDoc data) throws SAXException JavaDoc {
336         super.contentHandler.characters(data.toCharArray(), 0, data.length());
337     }
338 }
339
Popular Tags