2012-03-20 62 views
6

我有很多JasperReports報告包含複雜的SQL查詢,其中包含大量參數。這些報告用於生成包含查詢返回的數據的pdf文檔,並以各種方式進行分組和格式化。在我的Java項目中導出JasperReports查詢結果

現在我也需要直接導出查詢結果(例如ResultSet,或者Map或者csv文件,或者類似的...)。 是否有可能要求JasperReports僅執行查詢並返回結果而不是呈現PDF頁面? (注意:它與選擇csv輸出格式到報表呈現不同,因爲此方法試圖將報表設計轉換爲csv文件...相反,我只想「重用」報告中的查詢,JR也趁着參數管理,等...)

這是我的Java代碼從報表生成PDF文檔:

JasperReport report = (JasperReport) JRLoader.loadObject(inStream); 
JasperPrint jasperprint = JasperFillManager.fillReport(report, params, conn); 
JRAbstractExporter exporter = new JRPdfExporter(); 
exporter.exportReport(); 
ByteArrayOutputStream os = (ByteArrayOutputStream) exporter.getParameter(JRExporterParameter.OUTPUT_STREAM); 
byte[] formattedReportBytes = os.toByteArray(); 
return formattedReportBytes; 

我看到有一個叫JRJdbcQueryExecuter類內JasperReports ... 是否可以直接調用它而不是調用fillReport,爲了得到執行的SQL查詢的ResultSet?

感謝

+0

爲什麼你想使用JasperReports API來解決這個任務? – 2012-03-20 19:41:18

+0

正如我之前所說,我有很多報告,其中包含很長的SQL查詢(有很多參數)並生成複雜的pdf渲染,將數據分組在一起等等。現在我還必須提取數據庫查詢結果,而不進行任何處理,分組或呈現任何形式。這就像我手動複製報表中的查詢,我將所有$ P {}替換爲實際值,將其粘貼到SQL客戶端中,執行並將其作爲csv文件提取。我正在尋找一種自動的方式來做到這一點的代碼,利用JR參數管理和獲得解析的查詢和準備執行... – 2012-03-21 10:49:45

+0

這是什麼工作的目的?你將如何處理返回的ResultSet?只是有趣的...... – 2012-03-21 10:52:48

回答

7

我想開始與這感覺錯了,哈克,但它是可能的,減去執行查詢實際上有JasperReports的。

JasperReport report = (JasperReport) JRLoader.loadObject(inStream); 

//this is the actual query in the report 
JRQuery query = report.getMainDataSet().getQuery; 

//once here you get the entire sql string, this will have any parameters replaced with 
//the '?' character 
String queryString = query.getText(); 

//now start building your prepared statement, I am assuming you already have your 
//connection in the conn variable 
PrepararedStatment statement = con.prepareStatement(queryString); 

//almost there, need to set the parameters 
//the sql query is broke up into chunks inside the JRQuery. The chunks have types 
//that are either text, parameter, or parameter clause. We care about parameter, 
//not sure what parameter clause would be to be honest 
int index = 0; //this is the index to set the parameter at in the statement 
for (JRQueryChunk chunk : query.getChunks()){ 
    if (chunk.getType() == JRQueryChunk .TYPE_PARAMETER){ 
     statement.setObject(index, params.get(chunk.getText())); 
     index = index + 1; 
    } 
} 
//then execute the query 
ResultSet results = statement.executeQuery(); 

注:沒有錯誤檢查在這裏,你應該補充一點。也不確定是否這樣做是一個好主意。將查詢從報告中移出並放入Java代碼可能會更好。然後,只需傳入ResultSet作爲數據源,您就可以開始使用了。

+0

不起作用。 queryString仍然包含JR格式的參數(例如$ P {PARAM_1}),不會被解析。 我正在尋找一種方法來提取最終查詢作爲一個字符串,以手動執行它,或者一種方法來攔截JR執行它的時刻,並得到的結果,而不是繼續文檔渲染的時刻... – 2012-03-21 10:32:44

+0

你確定嗎,當我運行它的參數替換爲'?'時字符。通過JRQueryChunks循環怎麼樣?您可以重建查詢並用問號自己替換參數。 – 2012-03-21 13:04:51

+0

好吧,我改變了一下,現在它像一個魅力。謝謝! :) – 2012-03-23 16:29:50