将jasper文件转化为报表输出的代码

本文介绍了一个通用的报表导出组件,支持HTML、Excel和PDF三种格式的导出。该组件通过JasperReports实现,并提供了使用示例代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

不推荐用jsp, 用servlet 比较好,我这里有流程性的,你自己看着用吧,这东西用了2年,没发现问题。

通用的导出类,支持html,Excel,PDF三种

public class ReportType {

  
public static int HTML = 1;

  
public static int EXCEL = 2;

  
public static final int PDF = 3;

  
public static void export(HttpServletResponse response, JasperPrint jp, int type, String filename) throws Exception {
    JRExporter exporter 
= null;
    
if (type == HTML) {
      exporter 
= new JRHtmlExporter();
      exporter.setParameter(JRHtmlExporterParameter.IS_USING_IMAGES_TO_ALIGN, 
false);
      exporter.setParameter(JRHtmlExporterParameter.BETWEEN_PAGES_HTML, 
"");
      
// exporter.setParameter(JRHtmlExporterParameter.IS_REMOVE_EMPTY_SPACE_BETWEEN_ROWS, Boolean.TRUE);
    }
 else if (type == EXCEL) {
      exporter 
= new JRXlsExporter();
      response.setContentType(
"application/vnd.ms-excel");
      response.addHeader(
"Content-Disposition"new String(("attachment; filename=" + filename + ".xls").getBytes("GBK"), "ISO-8859-1"));
      exporter.setParameter(JRXlsExporterParameter.IS_ONE_PAGE_PER_SHEET, Boolean.FALSE);
      
// exporter.setParameter(JRXlsExporterParameter.IS_REMOVE_EMPTY_SPACE_BETWEEN_ROWS, Boolean.TRUE);
    }
 else if (type == PDF) {
      exporter 
= new JRPdfExporter();
      response.setContentType(
"application/pdf");
      response.addHeader(
"Content-Disposition"new String(("attachment; filename=" + filename + ".pdf").getBytes("GBK"), "ISO-8859-1"));
    }
 else {
      
return;
    }

    exporter.setParameter(JRExporterParameter.CHARACTER_ENCODING, 
"GBK");
    exporter.setParameter(JRExporterParameter.JASPER_PRINT, jp);
    exporter.setParameter(JRExporterParameter.OUTPUT_STREAM, response.getOutputStream());
    exporter.exportReport();
  }

}

 使用方法

String jasper = "jasper/saler/salerMonthSummary.jasper"// 你的jasper文件地址
String filename = "营销中心业务员" + from + "-" + to + "销售汇总"// 对于excel等需要下载的文件名

// 各种参数设置好
Map map = new HashMap();
map.put(
"YearFrom", from.getYear());
map.put(
"MonthFrom", from.getMonth());
map.put(
"YearTo", to.getYear());
map.put(
"MonthTo", to.getMonth());


// 读取jasper
JasperReport jr = (JasperReport) JRLoader.loadObjectFromLocation(jasper);

// 填充数据
JasperPrint jp = JasperFillManager.fillReport(jr, map, null);

// 判断是否正常
List<JRPrintPage> pages = jp.getPages();
if (pages.size() == 0{
  
// 没有数据
  return;
}


ReportType.export(response, jp, ReportType.EXCEL, filename);
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值