2008年9月30日 星期二

使用IReport 產生EXCEL檔的範例








JasperPrint jasperPrint;
JRResultSetDataSource jrds=null;
/* 帶參數進去給報表 */
Map map = new HashMap();
map.put("name","王小明");
Date d = new Date();
String Pdf_Name= (d.getYear()+1900)+"_"+(d.getMonth()+1)+"_"+d.getDate()+"_"+d.getHours()+"_"+d.getMinutes()+"_"+d.getSeconds();


try{
StrSQL = " SELECT SN, PRODUCT_TYPE, TC001, TD004, TD005, TD008, TB005_A, TA018_A, BAD_RATE_A, TA017_A, TB005_B, TA018_B, BAD_RATE_B, TA017_B, TB005_C, TA018_C, ";
StrSQL += " BAD_RATE_C, TA017_C, TB005_4, TA018_4, BAD_RATE_4, TA017_4, SUB_BAD_RATE ";
StrSQL += " FROM CARD_MOC013R ";
StrSQL += " ORDER BY PRODUCT_TYPE, TC001 ";
//out.println(StrSQL);

rs= stmt.executeQuery(StrSQL);


rs= stmt.executeQuery(StrSQL);
if(!rs.next()){
out.println("沒有資料,請重新查詢!!");
out.println("統計表");
}else{
rs.previous() ;
String fileName = application.getRealPath("MOC013R.jasper");
String outPath = application.getRealPath("MOC013R_"+Pdf_Name+".xls");
String outPath2 = application.getRealPath("MOC013R_"+Pdf_Name+".pdf");

File reportFile1 = new File(application.getRealPath("MOC013R.jasper"));

out.println("統計表_EXCEL版");



JasperPrint report = JasperFillManager.fillReport(fileName,map, new JRResultSetDataSource(rs));
JRAbstractExporter exporter = new JExcelApiExporter();
FileOutputStream output = new FileOutputStream(outPath);

exporter.setParameter(JRExporterParameter.JASPER_PRINT, report);
exporter.setParameter(JRXlsExporterParameter.IS_WHITE_PAGE_BACKGROUND, false);
exporter.setParameter(JRExporterParameter.OUTPUT_STREAM, output);
exporter.exportReport();
output.close();

JasperReport jasperReport = (JasperReport) JRLoader.loadObject(reportFile1.getPath());
jasperPrint = JasperFillManager.fillReport(jasperReport,map, new JRResultSetDataSource(rs));

JasperPrintManager.printReportToPdfFile(jasperPrint, outPath2);
/* 把報表轉換成 PDF, 給定 ( RecordSet, 輸出路徑 ) */
JasperExportManager.exportReportToPdfFile(jasperPrint,outPath2);
}

/* 連線關閉 */
} catch (JRException e) {
e.printStackTrace();
}

沒有留言: