KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > springframework > web > servlet > view > document > AbstractExcelView


1 /*
2  * Copyright 2002-2005 the original author or authors.
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
17 package org.springframework.web.servlet.view.document;
18
19 import java.util.Locale JavaDoc;
20 import java.util.Map JavaDoc;
21
22 import javax.servlet.ServletOutputStream JavaDoc;
23 import javax.servlet.http.HttpServletRequest JavaDoc;
24 import javax.servlet.http.HttpServletResponse JavaDoc;
25
26 import org.apache.poi.hssf.usermodel.HSSFCell;
27 import org.apache.poi.hssf.usermodel.HSSFRow;
28 import org.apache.poi.hssf.usermodel.HSSFSheet;
29 import org.apache.poi.hssf.usermodel.HSSFWorkbook;
30 import org.apache.poi.poifs.filesystem.POIFSFileSystem;
31
32 import org.springframework.core.io.Resource;
33 import org.springframework.core.io.support.LocalizedResourceHelper;
34 import org.springframework.web.servlet.support.RequestContextUtils;
35 import org.springframework.web.servlet.view.AbstractView;
36
37 /**
38  * Convenient superclass for Excel document views.
39  *
40  * <p>Properties:
41  * <ul>
42  * <li>url (optional): The url of an existing Excel document to pick as a starting point.
43  * It is done without localization part nor the ".xls" extension.
44  * </ul>
45  *
46  * <p>The file will be searched with locations in the following order:
47  * <ul>
48  * <li>[url]_[language]_[country].xls
49  * <li>[url]_[language].xls
50  * <li>[url].xls
51  * </ul>
52  *
53  * <p>For working with the workbook in the subclass, see
54  * <a HREF="http://jakarta.apache.org/poi/index.html">Jakarta's POI site</a>
55  *
56  * <p>As an example, you can try this snippet:
57  *
58  * <pre>
59  * protected void buildExcelDocument(
60  * Map model, HSSFWorkbook workbook,
61  * HttpServletRequest request, HttpServletResponse response) {
62  *
63  * // Go to the first sheet.
64  * // getSheetAt: only if workbook is created from an existing document
65  * // HSSFSheet sheet = workbook.getSheetAt(0);
66  * HSSFSheet sheet = workbook.createSheet("Spring");
67  * sheet.setDefaultColumnWidth(12);
68  *
69  * // Write a text at A1.
70  * HSSFCell cell = getCell(sheet, 0, 0);
71  * setText(cell, "Spring POI test");
72  *
73  * // Write the current date at A2.
74  * HSSFCellStyle dateStyle = workbook.createCellStyle();
75  * dateStyle.setDataFormat(HSSFDataFormat.getBuiltinFormat("m/d/yy"));
76  * cell = getCell(sheet, 1, 0);
77  * cell.setCellValue(new Date());
78  * cell.setCellStyle(dateStyle);
79  *
80  * // Write a number at A3
81  * getCell(sheet, 2, 0).setCellValue(458);
82  *
83  * // Write a range of numbers.
84  * HSSFRow sheetRow = sheet.createRow(3);
85  * for (short i = 0; i < 10; i++) {
86  * sheetRow.createCell(i).setCellValue(i * 10);
87  * }
88  * }</pre>
89  *
90  * This class is similar to the AbstractPdfView class in usage style.
91  *
92  * @author Jean-Pierre Pawlak
93  * @author Juergen Hoeller
94  * @see AbstractPdfView
95  */

96 public abstract class AbstractExcelView extends AbstractView {
97
98     /** The content type for an Excel response */
99     private static final String JavaDoc CONTENT_TYPE = "application/vnd.ms-excel";
100
101     /** The extension to look for existing templates */
102     private static final String JavaDoc EXTENSION = ".xls";
103
104
105     private String JavaDoc url;
106
107
108     /**
109      * Default Constructor.
110      * Sets the content type of the view to "application/vnd.ms-excel".
111      */

112     public AbstractExcelView() {
113         setContentType(CONTENT_TYPE);
114     }
115
116     /**
117      * Set the URL of the Excel workbook source, without localization part nor extension.
118      */

119     public void setUrl(String JavaDoc url) {
120         this.url = url;
121     }
122
123
124     /**
125      * Renders the Excel view, given the specified model.
126      */

127     protected final void renderMergedOutputModel(
128             Map JavaDoc model, HttpServletRequest JavaDoc request, HttpServletResponse JavaDoc response) throws Exception JavaDoc {
129
130         HSSFWorkbook workbook;
131         if (this.url != null) {
132             workbook = getTemplateSource(this.url, request);
133         }
134         else {
135             workbook = new HSSFWorkbook();
136             logger.debug("Created Excel Workbook from scratch");
137         }
138
139         buildExcelDocument(model, workbook, request, response);
140
141         // response.setContentLength(workbook.getBytes().length);
142
response.setContentType(getContentType());
143         ServletOutputStream JavaDoc out = response.getOutputStream();
144         workbook.write(out);
145         out.flush();
146     }
147
148     /**
149      * Creates the workbook from an existing XLS document.
150      * @param url the URL of the Excel template without localization part nor extension
151      * @param request current HTTP request
152      * @return the HSSFWorkbook
153      * @throws Exception in case of failure
154      */

155     protected HSSFWorkbook getTemplateSource(String JavaDoc url, HttpServletRequest JavaDoc request) throws Exception JavaDoc {
156         LocalizedResourceHelper helper = new LocalizedResourceHelper(getApplicationContext());
157         Locale JavaDoc userLocale = RequestContextUtils.getLocale(request);
158         Resource inputFile = helper.findLocalizedResource(url, EXTENSION, userLocale);
159
160         // Create the Excel document from the source.
161
if (logger.isDebugEnabled()) {
162             logger.debug("Loading Excel workbook from " + inputFile);
163         }
164         POIFSFileSystem fs = new POIFSFileSystem(inputFile.getInputStream());
165         HSSFWorkbook workBook = new HSSFWorkbook(fs);
166         return workBook;
167     }
168
169     /**
170      * Subclasses must implement this method to create an Excel HSSFWorkbook document,
171      * given the model.
172      * @param model the model Map
173      * @param workbook the Excel workbook to complete
174      * @param request in case we need locale etc. Shouldn't look at attributes.
175      * @param response in case we need to set cookies. Shouldn't write to it.
176      */

177     protected abstract void buildExcelDocument(
178             Map JavaDoc model, HSSFWorkbook workbook, HttpServletRequest JavaDoc request, HttpServletResponse JavaDoc response)
179             throws Exception JavaDoc;
180
181
182     /**
183      * Convenient method to obtain the cell in the given sheet, row and column.
184      * <p>Creates the row and the cell if they still doesn't already exist.
185      * Thus, the column can be passed as an int, the method making the needed downcasts.
186      * @param sheet a sheet object. The first sheet is usually obtained by workbook.getSheetAt(0)
187      * @param row thr row number
188      * @param col the column number
189      * @return the HSSFCell
190      */

191     protected HSSFCell getCell(HSSFSheet sheet, int row, int col) {
192         HSSFRow sheetRow = sheet.getRow(row);
193         if (sheetRow == null) {
194             sheetRow = sheet.createRow(row);
195         }
196         HSSFCell cell = sheetRow.getCell((short) col);
197         if (cell == null) {
198             cell = sheetRow.createCell((short) col);
199         }
200         return cell;
201     }
202
203     /**
204      * Convenient method to set a String as text content in a cell.
205      * @param cell the cell in which the text must be put
206      * @param text the text to put in the cell
207      */

208     protected void setText(HSSFCell cell, String JavaDoc text) {
209         cell.setCellType(HSSFCell.CELL_TYPE_STRING);
210         cell.setCellValue(text);
211     }
212
213 }
214
Popular Tags