ireport 导出工具类

Ireport 报表导出 Poi + ireport 导出pdf, word ,excel ,html 格式 下面是报表导出工具类

Ireport 报表导出 Poi + ireport 导出pdf, doc ,excel ,html 格式

下面是报表导出工具类reportExportUtils 需要导出以上格式的报表 只需要调用本工具类的exportmain 方法即可。

 

  1 package com.bzhinfo;
  2 
  3 import java.io.File;
  4 import java.io.FileInputStream;
  5 import java.io.FileNotFoundException;
  6 import java.io.IOException;
  7 import java.io.InputStream;
  8 import java.lang.reflect.Field;
  9 import java.util.Collection;
 10 import java.util.HashMap;
 11 import java.util.List;
 12 import java.util.Map;
 13 import javax.servlet.ServletOutputStream;
 14 import javax.servlet.http.HttpServletRequest;
 15 import javax.servlet.http.HttpServletResponse;
 16 import net.sf.jasperreports.engine.JRDataSource;
 17 import net.sf.jasperreports.engine.JRException;
 18 import net.sf.jasperreports.engine.JRExporter;
 19 import net.sf.jasperreports.engine.JRExporterParameter;
 20 import net.sf.jasperreports.engine.JasperExportManager;
 21 import net.sf.jasperreports.engine.JasperFillManager;
 22 import net.sf.jasperreports.engine.JasperPrint;
 23 import net.sf.jasperreports.engine.JasperReport;
 24 import net.sf.jasperreports.engine.base.JRBaseReport;
 25 import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
 26 import net.sf.jasperreports.engine.export.JRHtmlExporter;
 27 import net.sf.jasperreports.engine.export.JRHtmlExporterParameter;
 28 import net.sf.jasperreports.engine.export.JRRtfExporter;
 29 import net.sf.jasperreports.engine.export.JRXlsExporter;
 30 import net.sf.jasperreports.engine.export.JRXlsExporterParameter;
 31 import net.sf.jasperreports.engine.util.JRLoader;
 32 import org.apache.commons.lang.StringUtils;
 33 import org.apache.log4j.Logger;
 34 import org.apache.struts2.ServletActionContext;
 35 import com.opensymphony.xwork2.ActionContext;
 36 
 37 @SuppressWarnings("unchecked")
 38 public class JasperUtils {
 39 
 40     private static Logger logger = Logger.getLogger(JasperUtils.class);
 41     public static final String PRINT_TYPE = "print";
 42     public static final String PDF_TYPE = "pdf";
 43     public static final String EXCEL_TYPE = "excel";
 44     public static final String HTML_TYPE = "html";
 45     public static final String WORD_TYPE = "word";
 46 
 47     /**
 48      * 如果导出的是excel,则需要去掉周围的margin
 49      * 
 50      * @param jasperReport
 51      * @param type
 52      */
 53     public static void prepareReport(JasperReport jasperReport, String type) {
 54         logger
 55                 .debug("The method======= prepareReport() start.......................");
 56         if ("excel".equals(type))
 57             try {
 58                 Field margin = JRBaseReport.class
 59                         .getDeclaredField("leftMargin");
 60                 margin.setAccessible(true);
 61                 margin.setInt(jasperReport, 0);
 62                 margin = JRBaseReport.class.getDeclaredField("topMargin");
 63                 margin.setAccessible(true);
 64                 margin.setInt(jasperReport, 0);
 65                 margin = JRBaseReport.class.getDeclaredField("bottomMargin");
 66                 margin.setAccessible(true);
 67                 margin.setInt(jasperReport, 0);
 68                 Field pageHeight = JRBaseReport.class
 69                         .getDeclaredField("pageHeight");
 70                 pageHeight.setAccessible(true);
 71                 pageHeight.setInt(jasperReport, 2147483647);
 72             } catch (Exception exception) {
 73 
 74             }
 75 
 76     }
 77 
 78     /**
 79      * 导出Excel
 80      * 
 81      * @param jasperPrint
 82      * @param defaultFilename
 83      * @param request
 84      * @param response
 85      * @throws IOException
 86      * @throws JRException
 87      */
 88     public static void exportExcel(JasperPrint jasperPrint,
 89             String defaultFilename, HttpServletRequest request,
 90             HttpServletResponse response) throws IOException, JRException {
 91         logger
 92                 .debug("执行导出excel   The method======= exportExcel() start.......................");
 93         response.setContentType("application/vnd.ms-excel"); // 设置头文件信息
 94         String defaultname = null;
 95         if (defaultFilename.trim() != null && defaultFilename != null) {
 96             defaultname = defaultFilename + ".xls";
 97         } else {
 98             defaultname = "export.xls";
 99         }
100         String fileName = new String(defaultname.getBytes("gbk"), "utf-8");
101         response.setHeader("Content-disposition", "attachment; filename="
102                 + fileName);
103         ServletOutputStream ouputStream = response.getOutputStream();
104         JRXlsExporter exporter = new JRXlsExporter();
105         exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
106         exporter.setParameter(JRExporterParameter.OUTPUT_STREAM, ouputStream);
107         exporter.setParameter(
108                 JRXlsExporterParameter.IS_REMOVE_EMPTY_SPACE_BETWEEN_ROWS,
109                 Boolean.TRUE);
110         exporter.setParameter(JRXlsExporterParameter.IS_ONE_PAGE_PER_SHEET,
111                 Boolean.FALSE);
112         exporter.setParameter(JRXlsExporterParameter.IS_WHITE_PAGE_BACKGROUND,
113                 Boolean.FALSE);
114         exporter.exportReport();
115         ouputStream.flush();
116         ouputStream.close();
117     }
118 
119     /**
120      * 导出pdf,注意此处中文问题, 这里应该详细说:主要在ireport里变下就行了。看图
121      * 1)在ireport的classpath中加入iTextAsian.jar 2)在ireport画jrxml时,看ireport最左边有个属性栏。
122      * 下边的设置就在点字段的属性后出现。 pdf font name :STSong-Light ,pdf encoding :UniGB-UCS2-H
123      */
124     private static void exportPdf(JasperPrint jasperPrint,
125             String defaultFilename, HttpServletRequest request,
126             HttpServletResponse response) throws IOException, JRException {
127         response.setContentType("application/pdf");
128         String defaultname = null;
129         if (defaultFilename.trim() != null && defaultFilename != null) {
130             defaultname = defaultFilename + ".pdf";
131         } else {
132             defaultname = "export.pdf";
133         }
134         String fileName = new String(defaultname.getBytes("GBK"), "utf-8");
135         response.setHeader("Content-disposition", "attachment; filename="
136                 + fileName);
137         ServletOutputStream ouputStream = response.getOutputStream();
138         JasperExportManager.exportReportToPdfStream(jasperPrint, ouputStream);
139         ouputStream.flush();
140         ouputStream.close();
141     }
142 
143     /**
144      * 导出html
145      * 
146      * @param pageIndexStr
147      */
148 
149     private static void exportHtml(JasperPrint jasperPrint,
150             String defaultFilename, HttpServletRequest request,
151             HttpServletResponse response, String pageIndexStr)
152             throws IOException, JRException {
153         response.setContentType("text/html");
154         ServletOutputStream ouputStream = response.getOutputStream();
155         JRHtmlExporter exporter = new JRHtmlExporter();
156         Integer pageIndex = getPageIndex(jasperPrint, request, pageIndexStr); // 得到当前页码
157         if (pageIndex != null) { // 如果页码不为空 则设置分页页码
158             exporter.setParameter(JRExporterParameter.PAGE_INDEX, pageIndex);
159         }
160         exporter.setParameter(JRHtmlExporterParameter.IS_USING_IMAGES_TO_ALIGN,
161                 Boolean.FALSE);
162         exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
163         exporter.setParameter(JRExporterParameter.CHARACTER_ENCODING, "UTF-8");
164         exporter.setParameter(JRExporterParameter.OUTPUT_STREAM, ouputStream);
165         exporter.exportReport();
166         ouputStream.flush();
167         ouputStream.close();
168 
169     }
170 
171     /**
172      * description:通过传进来的pageIndexStr 得到当前页码 Date 2013-1-18 上午10:49:38
173      * 
174      * @param @param jasperPrint
175      * @param @param request
176      * @param @param pageIndexStr
177      * @param @return
178      * @return Integer
179      */
180     private static Integer getPageIndex(JasperPrint jasperPrint,
181             HttpServletRequest request, String pageIndexStr) {
182         if (pageIndexStr == null || StringUtils.isBlank(pageIndexStr)) { // 如果pageIndexStr为空或空字符串则返回null
183             return null;
184         }
185         Integer pageIndex = 0;
186         int lastPageIndex = 0;
187         if (jasperPrint.getPages() != null) { // 得到最后一页的 页码
188             lastPageIndex = jasperPrint.getPages().size() - 1;
189         }
190         if ("lastPage".equals(pageIndexStr)) { // 如果字符串==lastPage
191             // 则反lastPageIndex的值赋给pageIndex
192             // 并返回pageIndex
193             pageIndex = lastPageIndex;
194             return pageIndex;
195         }
196         try {
197             pageIndex = Integer.parseInt(pageIndexStr);
198             if (pageIndex > 0) { // 从ireport
199                 // 传来的PageIndex是从1开始,而JRExporterParameter.PAGE_INDEX是从0开始的
200                 pageIndex = pageIndex - 1;
201             }
202         } catch (Exception e) {
203             e.printStackTrace();
204         }
205         if (pageIndex < 0) {
206             pageIndex = 0;
207         }
208         if (pageIndex > lastPageIndex) {
209             pageIndex = lastPageIndex;
210         }
211         return pageIndex;
212     }
213 
214     /**
215      * 导出word
216      */
217 
218     private static void exportWord(JasperPrint jasperPrint,
219             String defaultFilename, HttpServletRequest request,
220             HttpServletResponse response) throws JRException, IOException {
221         response.setContentType("application/msword;charset=utf-8");
222         String defaultname = null;
223         if (defaultFilename.trim() != null && defaultFilename != null) {
224             defaultname = defaultFilename + ".doc";
225         } else {
226             defaultname = "export.doc";
227         }
228         String fileName = new String(defaultname.getBytes("GBK"), "utf-8");
229         response.setHeader("Content-disposition", "attachment; filename="
230                 + fileName);
231         JRExporter exporter = new JRRtfExporter();
232         exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
233         exporter.setParameter(JRExporterParameter.OUTPUT_STREAM, response
234                 .getOutputStream());
235         exporter.exportReport();
236     }
237 
238     /**
239      * 按照类型导出不同格式文件
240      * 
241      * @param datas
242      *            数据
243      * @param type
244      *            文件类型
245      * @param is
246      *            jasper文件的来源
247      * @param request
248      * @param response
249      * @param defaultFilename默认的导出文件的名称
250      */
251 
252     private static void export(Collection datas, String type,
253             String defaultFilename, InputStream is, HttpServletRequest request,
254             HttpServletResponse response, String pageIndexStr) {
255         logger
256                 .debug("导出判断     The method======= export() start.......................");
257         try {
258             logger.info("is==" + is);
259             JasperReport jasperReport = (JasperReport) JRLoader.loadObject(is);
260             prepareReport(jasperReport, type);
261             JRDataSource ds = new JRBeanCollectionDataSource(datas, false);
262             Map parameters = new HashMap();
263             JasperPrint jasperPrint = JasperFillManager.fillReport(
264                     jasperReport, parameters, ds);
265             if (EXCEL_TYPE.equals(type)) {
266                 exportExcel(jasperPrint, defaultFilename, request, response);
267             } else if (PDF_TYPE.equals(type)) {
268                 exportPdf(jasperPrint, defaultFilename, request, response);
269             } else if (HTML_TYPE.equals(type)) {
270                 exportHtml(jasperPrint, defaultFilename, request, response,
271                         pageIndexStr);
272             } else if (WORD_TYPE.equals(type)) {
273                 exportWord(jasperPrint, defaultFilename, request, response);
274             }
275         } catch (Exception e) {
276             e.printStackTrace();
277         }
278     }
279 
280     /**
281      * 导出入口 (导出所有的数据 )
282      * 
283      * @param exportType
284      *            导出文件的类型
285      * @param jaspername
286      *            jasper文件的名字 如: xx.jasper
287      * @param lists
288      *            导出的数据
289      * @param request
290      * @param response
291      * @param defaultFilename默认的导出文件的名称
292      */
293     public static void exportmain(String exportType, String jaspername,
294             List lists, String defaultFilename) {
295         exportmain(exportType, jaspername, lists, defaultFilename, null);
296     }
297 
298     /**
299      * 导出入口 (分页显示 导出传入的pageIndex 页的数据)
300      * 
301      * @param exportType
302      *            导出文件的类型
303      * @param jaspername
304      *            jasper文件的名字 如: xx.jasper
305      * @param lists
306      *            导出的数据
307      * @param request
308      * @param response
309      * @param defaultFilename默认的导出文件的名称
310      * @param pageIndex
311      *            需要导出数据的页码 当pageIndex = null时导出所有数据
312      */
313 
314     @SuppressWarnings("deprecation")
315     public static void exportmain(String exportType, String jaspername,
316             List lists, String defaultFilename, String pageIndexStr) {
317         logger
318                 .debug("进入导出    The method======= exportmain() start.......................");
319         ActionContext ct = ActionContext.getContext();
320         HttpServletRequest request = (HttpServletRequest) ct
321                 .get(ServletActionContext.HTTP_REQUEST);
322         HttpServletResponse response = ServletActionContext.getResponse();
323         String filenurl = request.getRealPath("/view/situation/jasper/"
324                 + jaspername);
325         File file = new File(filenurl);
326         InputStream is = null;
327         try {
328             is = new FileInputStream(file);
329         } catch (FileNotFoundException e) {
330             e.printStackTrace();
331         }
332         export(lists, exportType, defaultFilename, is, request, response,
333                 pageIndexStr);
334     }
335 
336 }

 

posted @ 2014-01-22 16:17  少爵  阅读(4546)  评论(0编辑  收藏  举报