从.jasper文件获取JasperPrint对象

时间:2013-07-17 09:17:00

标签: java jasper-reports

我正在尝试获取一个JRPrint对象,所以这里是代码:

import java.io.File;

import net.sf.jasperreports.engine.*;

public class TestClass {
 protected static JasperPrint jasperPrint;
 static JasperReport jasperReport;
 protected static JasperReportsContext jasperReportsContext;

 public static void main(String[] args) {
String fileName = "/home/amira/Desktop/Map/testReports/test/textreport.jasper";
boolean isXMLFile = false;

if (!isXMLFile && fileName.endsWith(".jrxml"))
{
    isXMLFile = true;
}

try
{
  loadReportJrprint(fileName, isXMLFile, DefaultJasperReportsContext.getInstance());
}
catch (JRException e)
{

    System.err.println("Error viewing report design."+ e);

    System.exit(1);
}

try {
  JasperExportManager.exportReportToPdfFile(fileName);
} catch (JRException e) {
  // TODO Auto-generated catch block
  e.printStackTrace();
}

 }


protected static void loadReportJrprint(String fileName, boolean isXmlReport, JasperReportsContext jasperReportsContext) throws JRException
{
    if (isXmlReport)
    {
      jasperPrint = JRPrintXmlLoader.loadFromFile(jasperReportsContext, fileName);
      System.out.println(jasperPrint.getName());

    }
    else
    {
      jasperPrint = (JasperPrint)JRLoader.loadObjectFromFile(fileName);
    }

}
}

但是我收到了这个错误:

Exception in thread "main" java.lang.ClassCastException: net.sf.jasperreports.engine.JasperReport cannot be cast to net.sf.jasperreports.engine.JasperPrint
at TestClass.loadReportJrprint(TestClass.java:80)
at TestClass.main(TestClass.java:50)

1 个答案:

答案 0 :(得分:3)

.jasper文件是mereley编译的.jrxml,因此您检索的是JasperReport对象,它描述了编译的模板。要获取描述准备查看或导出的文档的JasperPrint对象,您必须首先使用JasperFillManager.fill方法之一填充报告。请参阅the javadoc for JasperFillManager