KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > net > sf > jasperreports > engine > export > JRCsvExporter


1 /*
2  * ============================================================================
3  * GNU Lesser General Public License
4  * ============================================================================
5  *
6  * JasperReports - Free Java report-generating library.
7  * Copyright (C) 2001-2006 JasperSoft Corporation http://www.jaspersoft.com
8  *
9  * This library is free software; you can redistribute it and/or
10  * modify it under the terms of the GNU Lesser General Public
11  * License as published by the Free Software Foundation; either
12  * version 2.1 of the License, or (at your option) any later version.
13  *
14  * This library is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
17  * Lesser General Public License for more details.
18  *
19  * You should have received a copy of the GNU Lesser General Public
20  * License along with this library; if not, write to the Free Software
21  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
22  *
23  * JasperSoft Corporation
24  * 303 Second Street, Suite 450 North
25  * San Francisco, CA 94107
26  * http://www.jaspersoft.com
27  */

28
29 /*
30  * Contributors:
31  * Mirko Wawrowsky - mawawrosky@users.sourceforge.net
32  */

33 package net.sf.jasperreports.engine.export;
34
35 import java.io.File JavaDoc;
36 import java.io.FileOutputStream JavaDoc;
37 import java.io.IOException JavaDoc;
38 import java.io.OutputStream JavaDoc;
39 import java.io.OutputStreamWriter JavaDoc;
40 import java.io.StringWriter JavaDoc;
41 import java.io.Writer JavaDoc;
42 import java.util.List JavaDoc;
43 import java.util.StringTokenizer JavaDoc;
44
45 import net.sf.jasperreports.engine.JRAbstractExporter;
46 import net.sf.jasperreports.engine.JRException;
47 import net.sf.jasperreports.engine.JRExporterParameter;
48 import net.sf.jasperreports.engine.JRPrintElement;
49 import net.sf.jasperreports.engine.JRPrintPage;
50 import net.sf.jasperreports.engine.JRPrintText;
51 import net.sf.jasperreports.engine.JasperPrint;
52 import net.sf.jasperreports.engine.util.JRStyledText;
53 import net.sf.jasperreports.engine.util.JRStyledTextParser;
54
55 import org.xml.sax.SAXException JavaDoc;
56
57
58 /**
59  * Exports a JasperReports document to CSV format. It has character output type and exports the document to a
60  * grid-based layout.
61  * @author Teodor Danciu (teodord@users.sourceforge.net)
62  * @version $Id: JRCsvExporter.java 1528 2006-12-21 16:03:55 +0200 (Thu, 21 Dec 2006) teodord $
63  */

64 public class JRCsvExporter extends JRAbstractExporter
65 {
66
67
68     /**
69      *
70      */

71     protected JRStyledTextParser styledTextParser = new JRStyledTextParser();
72
73     /**
74      *
75      */

76     protected String JavaDoc delimiter = null;
77
78     /**
79      *
80      */

81     protected String JavaDoc recordDelimiter = null;
82
83     /**
84      *
85      */

86     protected Writer JavaDoc writer = null;
87     protected JRExportProgressMonitor progressMonitor = null;
88
89     
90     /**
91      *
92      */

93     public void exportReport() throws JRException
94     {
95         progressMonitor = (JRExportProgressMonitor)parameters.get(JRExporterParameter.PROGRESS_MONITOR);
96         
97         /* */
98         setOffset();
99
100         /* */
101         setInput();
102
103         /* */
104         if (!isModeBatch)
105         {
106             setPageRange();
107         }
108
109         String JavaDoc encoding = (String JavaDoc)parameters.get(JRExporterParameter.CHARACTER_ENCODING);
110         if (encoding == null)
111         {
112             encoding = "ISO-8859-1";
113         }
114         
115         delimiter = (String JavaDoc)parameters.get(JRCsvExporterParameter.FIELD_DELIMITER);
116         if (delimiter == null)
117         {
118             delimiter = ",";
119         }
120         
121         recordDelimiter = (String JavaDoc)parameters.get(JRCsvExporterParameter.RECORD_DELIMITER);
122         if (recordDelimiter == null)
123         {
124             recordDelimiter = "\n";
125         }
126         
127         StringBuffer JavaDoc sb = (StringBuffer JavaDoc)parameters.get(JRExporterParameter.OUTPUT_STRING_BUFFER);
128         if (sb != null)
129         {
130             try
131             {
132                 writer = new StringWriter JavaDoc();
133                 exportReportToWriter();
134                 sb.append(writer.toString());
135             }
136             catch (IOException JavaDoc e)
137             {
138                 throw new JRException("Error writing to StringBuffer writer : " + jasperPrint.getName(), e);
139             }
140             finally
141             {
142                 if (writer != null)
143                 {
144                     try
145                     {
146                         writer.close();
147                     }
148                     catch(IOException JavaDoc e)
149                     {
150                     }
151                 }
152             }
153         }
154         else
155         {
156             writer = (Writer JavaDoc)parameters.get(JRExporterParameter.OUTPUT_WRITER);
157             if (writer != null)
158             {
159                 try
160                 {
161                     exportReportToWriter();
162                 }
163                 catch (IOException JavaDoc e)
164                 {
165                     throw new JRException("Error writing to writer : " + jasperPrint.getName(), e);
166                 }
167             }
168             else
169             {
170                 OutputStream JavaDoc os = (OutputStream JavaDoc)parameters.get(JRExporterParameter.OUTPUT_STREAM);
171                 if (os != null)
172                 {
173                     try
174                     {
175                         writer = new OutputStreamWriter JavaDoc(os, encoding);
176                         exportReportToWriter();
177                     }
178                     catch (IOException JavaDoc e)
179                     {
180                         throw new JRException("Error writing to OutputStream writer : " + jasperPrint.getName(), e);
181                     }
182                 }
183                 else
184                 {
185                     File JavaDoc destFile = (File JavaDoc)parameters.get(JRExporterParameter.OUTPUT_FILE);
186                     if (destFile == null)
187                     {
188                         String JavaDoc fileName = (String JavaDoc)parameters.get(JRExporterParameter.OUTPUT_FILE_NAME);
189                         if (fileName != null)
190                         {
191                             destFile = new File JavaDoc(fileName);
192                         }
193                         else
194                         {
195                             throw new JRException("No output specified for the exporter.");
196                         }
197                     }
198
199                     try
200                     {
201                         os = new FileOutputStream JavaDoc(destFile);
202                         writer = new OutputStreamWriter JavaDoc(os, encoding);
203                         exportReportToWriter();
204                     }
205                     catch (IOException JavaDoc e)
206                     {
207                         throw new JRException("Error writing to file writer : " + jasperPrint.getName(), e);
208                     }
209                     finally
210                     {
211                         if (writer != null)
212                         {
213                             try
214                             {
215                                 writer.close();
216                             }
217                             catch(IOException JavaDoc e)
218                             {
219                             }
220                         }
221                     }
222                 }
223             }
224         }
225     }
226
227
228     /**
229      *
230      */

231     protected void exportReportToWriter() throws JRException, IOException JavaDoc
232     {
233         for(int reportIndex = 0; reportIndex < jasperPrintList.size(); reportIndex++)
234         {
235             jasperPrint = (JasperPrint)jasperPrintList.get(reportIndex);
236
237             List JavaDoc pages = jasperPrint.getPages();
238             if (pages != null && pages.size() > 0)
239             {
240                 if (isModeBatch)
241                 {
242                     startPageIndex = 0;
243                     endPageIndex = pages.size() - 1;
244                 }
245
246                 for(int i = startPageIndex; i <= endPageIndex; i++)
247                 {
248                     if (Thread.currentThread().isInterrupted())
249                     {
250                         throw new JRException("Current thread interrupted.");
251                     }
252                 
253                     JRPrintPage page = (JRPrintPage)pages.get(i);
254
255                     /* */
256                     exportPage(page);
257                 }
258             }
259         }
260                 
261         writer.flush();
262     }
263
264
265     /**
266      *
267      */

268     protected void exportPage(JRPrintPage page) throws IOException JavaDoc
269     {
270         JRGridLayout layout = new JRGridLayout(page.getElements(), null,
271                 jasperPrint.getPageWidth(), jasperPrint.getPageHeight(), globalOffsetX, globalOffsetY,
272                 JRGridLayout.TEXT_EXPORTER,
273                 true, false, false, null);
274         
275         JRExporterGridCell[][] grid = layout.getGrid();
276         boolean[] isRowUsed = layout.getIsRowNotEmpty();
277         boolean[] isColUsed = layout.getIsColumnNotEmpty();
278
279         StringBuffer JavaDoc rowbuffer = null;
280         
281         JRPrintElement element = null;
282         String JavaDoc text = null;
283         boolean isFirstColumn = true;
284         for(int y = 0; y < grid.length; y++)
285         {
286             rowbuffer = new StringBuffer JavaDoc();
287
288             if (isRowUsed[y])
289             {
290                 isFirstColumn = true;
291                 for(int x = 0; x < grid[y].length; x++)
292                 {
293                     if(grid[y][x].element != null)
294                     {
295                         element = grid[y][x].element;
296     
297                         if (element instanceof JRPrintText)
298                         {
299                             JRStyledText styledText = getStyledText((JRPrintText)element);
300                             if (styledText == null)
301                             {
302                                 text = "";
303                             }
304                             else
305                             {
306                                 text = styledText.getText();
307                             }
308                             
309                             if (!isFirstColumn)
310                             {
311                                 rowbuffer.append(delimiter);
312                             }
313                             rowbuffer.append(
314                                 prepareText(text)
315                                 );
316                             isFirstColumn = false;
317                         }
318                     }
319                     else
320                     {
321                         if (isColUsed[x])
322                         {
323                             if (!isFirstColumn)
324                             {
325                                 rowbuffer.append(delimiter);
326                             }
327                             isFirstColumn = false;
328                         }
329                     }
330                 }
331                 
332                 if (rowbuffer.length() > 0)
333                 {
334                     writer.write(rowbuffer.toString());
335                     writer.write(recordDelimiter);
336                 }
337             }
338         }
339         
340         if (progressMonitor != null)
341         {
342             progressMonitor.afterPageExport();
343         }
344     }
345     
346     
347     /**
348      *
349      */

350     protected JRStyledText getStyledText(JRPrintText textElement)
351     {
352         JRStyledText styledText = null;
353
354         String JavaDoc text = textElement.getText();
355         if (text != null)
356         {
357             if (textElement.isStyledText())
358             {
359                 try
360                 {
361                     styledText = styledTextParser.parse(null, text);
362                 }
363                 catch (SAXException JavaDoc e)
364                 {
365                     //ignore if invalid styled text and treat like normal text
366
}
367             }
368         
369             if (styledText == null)
370             {
371                 styledText = new JRStyledText();
372                 styledText.append(text);
373                 styledText.addRun(new JRStyledText.Run(null, 0, text.length()));
374             }
375         }
376         
377         return styledText;
378     }
379
380
381     /**
382      *
383      */

384     protected String JavaDoc prepareText(String JavaDoc source)
385     {
386         String JavaDoc str = null;
387         
388         if (source != null)
389         {
390             boolean putQuotes = false;
391             
392             if (source.indexOf(delimiter) >= 0)
393             {
394                 putQuotes = true;
395             }
396             
397             StringBuffer JavaDoc sbuffer = new StringBuffer JavaDoc();
398             StringTokenizer JavaDoc tkzer = new StringTokenizer JavaDoc(source, "\"\n", true);
399             String JavaDoc token = null;
400             while(tkzer.hasMoreTokens())
401             {
402                 token = tkzer.nextToken();
403                 if ("\"".equals(token))
404                 {
405                     putQuotes = true;
406                     sbuffer.append("\"\"");
407                 }
408                 else if ("\n".equals(token))
409                 {
410                     //sbuffer.append(" ");
411
putQuotes = true;
412                     sbuffer.append("\n");
413                 }
414                 else
415                 {
416                     sbuffer.append(token);
417                 }
418             }
419             
420             str = sbuffer.toString();
421             
422             if (putQuotes)
423             {
424                 str = "\"" + str + "\"";
425             }
426         }
427         
428         return str;
429     }
430
431
432 }
433
Popular Tags