jFreeChart 编译和生成报表

报表源文件(后缀名为[color=violet].jrxml[/color])在[color=violet]iReport[/color]的图形化界面中编辑和预览更方便。也可以在程序中通过代码来实现编译、填充和预览:

流程:
[color=darkblue]a[/color]. 首先检查编译后的文件是否存在,没有就编译并保存结果(后缀名为[color=violet].jasper[/color])到该目录(因为编译耗时较长,除非源文件改变,尽量减少编译次数)。
[color=darkblue]b[/color]. 加载编译文件,填充报表数据,生成可打印的报表。
[color=darkblue]c[/color]. 把该报表添加到窗体中预览。


import net.sf.jasperreports.engine.*;

public class Report {
public void processReport(Object[] arrData) {
// Encapsulate an array of report beans
JRBeanArrayDataSource dataSource = new JRBeanArrayDataSource(arrData);
// Additional data could be put into map
Map map = new HashMap();
map.put("title", "gorgeous");
// Get the compiled report file
String plainPath= "D:\xml";
File compiledFile = new File(plainPath, "report1.jasper");
// Check whether it exists, if not, compile the source and save the compiled result as a file
checkAndCompileJRXML(compiledFile);
// Likewise, check whether the sub reports invoked by the main report exists.
checkAndCompileJRXML(plainPath, "report1_sub.jasper");
// Load the report from the specified file
JasperReport jasperReport = (JasperReport)JRLoader.loadObject(compiledFile);
// Fill the report with the data of beans as well as additional info (map)
JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, map, beanDataSource);
// Add the JasperPrint object to a swing panel to show
showReport(jasperPrint);
}

public void showReport(JasperPrint jasperPrint) {
JRViewer viewer = new JRViewer(jasperPrint);
JFrame frame = new JFrame();
JPanel panel = new JPanel();
LayoutManager layout = new BorderLayout();
panel.setLayout(layout);
JRViewer viewer = new JRViewer(jasperPrint);
panel.add(viewer, BorderLayout.CENTER);
frame.getContentPane().add(panel);
frame.setVisible(true);
}

// Combine two report together if needed
private JasperPrint combineReport(JasperPrint jasperPrint, JasperPrint jasperPrint2) {
List pages = jasperPrint2.getPages();
for (int i = 0; i < pages.size(); i++) {
JRPrintPage page = (JRPrintPage)pages.get(i);
jasperPrint.addPage(page);
}
return jasperPrint;
}

private void checkAndCompileJRXML(String path, String name) throws JRException {
File file = new File(path.concat(name));
checkAndCompileJRXML(file);
}

private void checkAndCompileJRXML(File file) throws JRException {
if (!file.exists()) { // Compiled report file doesn't exist
String compiledName = file.getPath();
int idx = compiledName.lastIndexOf('.');
// Get the source report file
String sourceName = compiledName.substring(0, idx+1).concat("jrxml");
file = new File(sourceName);
// Compile the source file and save the compiled report
JasperCompileManager.compileReportToFile(file.getPath());
}
}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值