2012-12-20 64 views
0

JasperReport有一些問題。我通過iReport生成了一個* .jrxml文件。 那裏我定義了一些領域。現在我想在我的Java應用程序中設置這些字段,但它不起作用。JasperReport設置參數

我的代碼看起來像

JasperReport report; 
    JasperPrint print; 

    HashMap<String, Object> parameters = new HashMap<String, Object>(); 

    parameters.put("logoPath", "\\logo.jpg"); 
    parameters.put("companyName", "Company Name"); 

    try { 
     report = JasperCompileManager 
       .compileReport("JRXML\\Template.jrxml"); 

     for (JRField field : report.getFields()) { 
      System.out.println(field.getName() + "|" 
        + field.getValueClassName()); 
     } 

     print = JasperFillManager.fillReport(report, parameters, 
       new JREmptyDataSource()); 
     JasperExportManager.exportReportToPdfFile(print, 
       "\\temp\\Example.pdf"); 

     JasperViewer.viewReport(print); 

    } catch (Exception e) { 
     // TODO Auto-generated catch block 
     Logger.getLogger(Example1.class.getName()).log(Level.ALL, 
       e.getLocalizedMessage()); 

     e.printStackTrace(); 
    } 

的字段在*的.jrxml文件中給出。

感謝您的幫助

+0

您是在談論領域或參數?我看到你只打印出了字段,從不設置它們。 – gresdiplitude

+0

在.jrxml文件中,我定義了名稱爲logoPath和companyName的字段。我讀過的教程中他們說我可以使用HashMap設置字段,其中鍵是字段名稱。我想用fillReport()方法設置參數 – ZeusNet

回答

3

您在混淆參數和字段。參數定義爲<parameter name="companyName" class="java.lang.String" isForPrompting="false">,而字段定義爲<field name="companyName" class="java.lang.String"/>。將公司名稱轉換爲jrxml中的參數,它應該可以工作。

this教程

參數

參數是傳入的填充行動的報告 對象的引用。它們非常有用,可以傳遞在其數據源中通常無法找到的報表 引擎數據。

報告字段代表從數據源 數據映射到報告生成程序的唯一途徑。當 報告的數據源是ResultSet時,所有字段都必須映射到ResultSet對象的相應列中。也就是說,它們必須與它們映射的 列以及兼容類型具有相同的名稱。

原來的答案:

使用FileResolver爲logo.jpg,這碧玉用來解析文件的位置。

FileResolver fileResolver = new FileResolver() { 
@Override 
public File resolveFile(String fileName) { 
URI uri = null; 
try { 
uri = new URI(this.getClass().getResource("/" + fileName).getPath()); 
} catch (URISyntaxException e) { 
} 
return new File(uri.getPath()); 
} 
}; 

HashMap<String, Object> parameters = new HashMap<String, Object>(); 

parameters.put("logoPath", "\\logo.jpg"); 
parameters.put("companyName", "Company Name"); 
parameters.put("REPORT_FILE_RESOLVER", fileResolver); 
... 
print = JasperFillManager.fillReport(report, parameters, 
new JREmptyDataSource()); 
+0

感謝您的回答,但沒有解決問題。在pdf文件中,所有字段都顯示爲空。 – ZeusNet

+0

好吧我建議只是從java代碼和jrxml註釋掉logo.jpg的部分,然後運行它,如果出現「公司名稱」,那麼這是一個文件解析器問題,否則參數有問題。 – gresdiplitude

+0

我已經在xml和java應用程序中註釋了字段logoPath,但companyName的值仍然爲空。 – ZeusNet