2013-07-17 63 views
0

我試圖讓JRPrint對象,因此這裏JasperPrint對象的代碼:充分利用.jasper文件,然後

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) 

回答

3

一個.jasper文件mereley編譯爲.jrxml,因此您要檢索的是描述編譯模板的JasperReport對象。要獲取JasperPrint對象,該對象描述準備查看或導出的文檔,您必須先用JasperFillManager.fill方法之一填寫報告。見the javadoc for JasperFillManager