JasperHelper 工具类

package org.platform.service.report.oauth;


import java.io.File;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Field;
import java.sql.Connection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


import net.sf.jasperreports.engine.JRDataSource;
import net.sf.jasperreports.engine.JRExporterParameter;
import net.sf.jasperreports.engine.JRParameter;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.engine.base.JRBaseReport;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
import net.sf.jasperreports.engine.export.JRHtmlExporter;
import net.sf.jasperreports.engine.export.JRHtmlExporterParameter;
import net.sf.jasperreports.engine.export.JRPdfExporter;
import net.sf.jasperreports.engine.export.ooxml.JRXlsxExporter;
import net.sf.jasperreports.engine.fill.JRFileVirtualizer;
import net.sf.jasperreports.engine.util.JRLoader;
import net.sf.jasperreports.export.SimpleExporterInput;
import net.sf.jasperreports.export.SimpleOutputStreamExporterOutput;
import net.sf.jasperreports.export.SimplePdfExporterConfiguration;
import net.sf.jasperreports.export.SimpleXlsxReportConfiguration;


import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.platform.service.report.config.ReportConfig;
import org.platform.utils.file.FileUtil;


@SuppressWarnings("deprecation")
public class JasperHelper
{


private static final Logger logger = Logger.getLogger(JasperHelper.class);


/**
* @Description 导出EXCEL、HTML、PDF文件入口
* @MethodName export
* @Author L_X
* @Date 2017年7月28日 下午4:56:09
* @param lists 数据集
* @param type 文件类型
* @param fileName 文件名称
* @param is 输入流
* @param request
* @param response
* @throws Exception void
*/
public static void export(List<?> lists, String type, String fileName, String params, InputStream is,Connection connection, HttpServletRequest request, HttpServletResponse response,String querySqlParams) throws Exception
{
logger.debug("导出判断     The method======= export() start.......................");
JasperReport jasperReport = (JasperReport) JRLoader.loadObject(is);
preparReport(jasperReport, type);
JRDataSource jrDataSource = new JRBeanCollectionDataSource(lists, false);
Map<String, Object> map = new HashMap<String, Object>();
// params = StringEscapeUtils.unescapeHtml4(params);
// map = JSONUtils.parseJSON(params);
Map<String, String> paramMap = JasperReportUtil.processingParams(params, querySqlParams);
for(Entry<String, String> en : paramMap.entrySet()){
map.put(en.getKey(), en.getValue());
}
map.put("REPORT_CONNECTION", connection);
map.put("SUBREPORT_DIR", ReportConfig.HTTP_GET_REPORT_FILE);
//导出数据缓存路径
String cachePath = request.getSession().getServletContext().getRealPath("/") + "cacheDir\\";
FileUtil.mkDir(cachePath);
JRFileVirtualizer virtualizer = new JRFileVirtualizer(2, cachePath);
virtualizer.setReadOnly(true);
map.put(JRParameter.REPORT_VIRTUALIZER, virtualizer);
JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, map, jrDataSource);
fileName = StringUtils.isNotBlank(fileName) ? fileName : "export";
if (DefaultConstants.TYPE_EXCEL.equals(type))
{
exportExcel(jasperPrint, fileName + ".xlsx", response);
}
else if (DefaultConstants.TYPE_HTML.equals(type))
{
exportHtml(jasperPrint, fileName + ".html", response);
}
else if (DefaultConstants.TYPE_PDF.equals(type))
{
exportPdf(jasperPrint, fileName + ".pdf", response);
}
virtualizer.cleanup();
lists.clear();
}


/**
* @Description 如果导出的是excel,则需要去掉周围的margin
* @MethodName preparReport
* @Author L_X
* @Date 2017年7月28日 下午12:14:57
* @param jasperReport
* @param type void
*/
public static void preparReport(JasperReport jasperReport, String type)
{
if ("EXCEL".equals(type))
{
try
{
Field margin = JRBaseReport.class.getDeclaredField("leftMargin");
margin.setAccessible(true);
margin.setInt(jasperReport, 0);
margin = JRBaseReport.class.getDeclaredField("topMargin");
margin.setAccessible(true);
margin.setInt(jasperReport, 0);
margin = JRBaseReport.class.getDeclaredField("bottomMargin");
margin.setAccessible(true);
margin.setInt(jasperReport, 0);
Field pageHeight = JRBaseReport.class.getDeclaredField("pageHeight");
pageHeight.setAccessible(true);
pageHeight.setInt(jasperReport, 2147483647);
} catch (Exception exception)
{
}
}
}


/**
* @Description 导出EXCEL文件
* @MethodName exportExcel
* @Author L_X
* @Date 2017年7月28日 下午4:11:53
* @param jasperPrint
* @param defaultFileName
* @param request
* @param response
* @throws Exception void
*/
public static void exportExcel(JasperPrint jasperPrint, String fileName, HttpServletResponse response) throws Exception
{
logger.info("执行导出EXCEL   The method======= exportExcel() start.......................");
response.setContentType("application/vnd.ms-excel");
fileName = new String(fileName.getBytes("GBK"), "UTF-8");
response.setHeader("Content-disposition", "attachment; filename=" + fileName);
JRXlsxExporter jrXlsxExporter = new JRXlsxExporter();
jrXlsxExporter.setExporterInput(new SimpleExporterInput(jasperPrint));
jrXlsxExporter.setExporterOutput(new SimpleOutputStreamExporterOutput(response.getOutputStream()));
SimpleXlsxReportConfiguration configuration = new SimpleXlsxReportConfiguration();
configuration.setMaxRowsPerSheet(DefaultConstants.MAX_NUM_EXCEL);
configuration.setRemoveEmptySpaceBetweenRows(Boolean.TRUE);
configuration.setRemoveEmptySpaceBetweenColumns(Boolean.FALSE);
configuration.setOnePagePerSheet(Boolean.FALSE);
configuration.setDetectCellType(Boolean.TRUE);
configuration.setWhitePageBackground(Boolean.FALSE);
configuration.setCollapseRowSpan(Boolean.FALSE);
configuration.setFontSizeFixEnabled(Boolean.TRUE);
jrXlsxExporter.setConfiguration(configuration);
jrXlsxExporter.exportReport();
jrXlsxExporter.reset();
logger.info("执行导出EXCEL   The method======= exportExcel() end.......................");
}


/**
* @Description 导出HTML文件
* @MethodName exportHtml
* @Author L_X
* @Date 2017年7月28日 下午4:17:05
* @param jasperPrint
* @param fileName
* @param request
* @param response
* @throws Exception void
*/
public static void exportHtml(JasperPrint jasperPrint, String fileName, HttpServletResponse response) throws Exception
{
logger.info("执行导出HTML   The method======= exportHtml() start.......................");
response.setContentType("text/html");
fileName = new String(fileName.getBytes("GBK"), "UTF-8");
response.setHeader("Content-disposition", "attachment; filename=" + fileName);
JRHtmlExporter exporter = new JRHtmlExporter();
exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
exporter.setParameter(JRExporterParameter.OUTPUT_STREAM, response.getOutputStream());
exporter.setParameter(JRHtmlExporterParameter.IS_USING_IMAGES_TO_ALIGN, Boolean.FALSE);
exporter.setParameter(JRHtmlExporterParameter.HTML_HEADER, "");
exporter.setParameter(JRHtmlExporterParameter.BETWEEN_PAGES_HTML, "");
File imgRealDir = createChartImage();
//重设JRHtmlExporterParameter.IMAGES_URI  
exporter.setParameter(JRHtmlExporterParameter.IMAGES_URI, imgRealDir.getPath() + "/");
exporter.setParameter(JRHtmlExporterParameter.IMAGES_DIR, imgRealDir);
exporter.setParameter(JRHtmlExporterParameter.IS_OUTPUT_IMAGES_TO_DIR, Boolean.TRUE);
exporter.setParameter(JRHtmlExporterParameter.HTML_FOOTER, "");
exporter.exportReport();
logger.info("执行导出HTML   The method======= exportHtml() end.......................");
}
/**
* @Description 页面展示
* @MethodName exportHtml
* @Author L_X
* @Date 2017年9月7日 下午12:33:40
* @param is
* @param os
* @param map
* @param dbSource
* @throws Exception void
*/
public static void jasperToHtml(InputStream is, OutputStream os, Map<String, Object> map, Connection connection) throws Exception{
JasperReport jasperReport = (JasperReport) JRLoader.loadObject(is);
JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, map, connection);
JRHtmlExporter exporter = new JRHtmlExporter();
exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
exporter.setParameter(JRExporterParameter.OUTPUT_STREAM, os);
exporter.setParameter(JRHtmlExporterParameter.IS_USING_IMAGES_TO_ALIGN, Boolean.FALSE);
exporter.setParameter(JRHtmlExporterParameter.HTML_HEADER, "");
exporter.setParameter(JRHtmlExporterParameter.BETWEEN_PAGES_HTML, "");
File imgRealDir = createChartImage();
//重设JRHtmlExporterParameter.IMAGES_URI  
exporter.setParameter(JRHtmlExporterParameter.IMAGES_URI, imgRealDir.getPath() + "/");
exporter.setParameter(JRHtmlExporterParameter.IMAGES_DIR, imgRealDir);
exporter.setParameter(JRHtmlExporterParameter.IS_OUTPUT_IMAGES_TO_DIR, Boolean.TRUE);
exporter.setParameter(JRHtmlExporterParameter.HTML_FOOTER, "");
exporter.exportReport();
}


/**
* @Description 导出PDF文件
* @MethodName exportPdf
* @Author L_X
* @Date 2017年7月28日 下午4:22:53
* @param jasperPrint
* @param fileName
* @param request
* @param response
* @throws Exception void
*/
public static void exportPdf(JasperPrint jasperPrint, String fileName, HttpServletResponse response) throws Exception
{
logger.info("执行导出PDF   The method======= exportPdf() start.......................");
response.setContentType("application/pdf");
fileName = new String(fileName.getBytes("GBK"), "UTF-8");
response.setHeader("Content-disposition", "attachment; filename=" + fileName);
JRPdfExporter jrPdfExporter = new JRPdfExporter();
OutputStream os = response.getOutputStream();
jrPdfExporter.setExporterInput(new SimpleExporterInput(jasperPrint));
jrPdfExporter.setExporterOutput(new SimpleOutputStreamExporterOutput(os));
SimplePdfExporterConfiguration configuration = new SimplePdfExporterConfiguration();
jrPdfExporter.setConfiguration(configuration);
jrPdfExporter.exportReport();
os.close();
logger.info("执行导出PDF   The method======= exportPdf() end.......................");
}


/**
* @Description 创建Chart图表文件夹
* @MethodName createChartImage
* @Author L_X
* @Date 2017年8月10日 上午9:42:08
* @return File
*/
public static File createChartImage()
{
String imgPathWrite = ReportConfig.HTTP_GET_CHART_WRITE_PATH;
String imgPath = imgPathWrite.replace("/", File.separator);
File imgRealDir = new File(imgPath);
if (!imgRealDir.exists())
{
imgRealDir.mkdirs();
}
logger.info("graph图片写入路径" + ReportConfig.HTTP_GET_CHART_WRITE_PATH);
return imgRealDir;
}


/**
* @Description 获取Chart图表预存路径
* @MethodName getFilePath
* @Author L_X
* @Date 2017年8月10日 上午9:10:00
* @return String
*/
public static String getChartImgPath()
{
//报表图片生成路径 
//URL url = Thread.currentThread().getContextClassLoader().getResource("");
//String filePath = url.getFile().substring(1, url.getFile().length());
//return filePath + "static/images/" + IREPORT_IMG;


logger.info("graph图片读取路径" + ReportConfig.HTTP_GET_CHART_READ_PATH);
String saveUrl = ReportConfig.HTTP_GET_CHART_READ_PATH;
return saveUrl;
}
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值