jFreeChart 编译和生成报表

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

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

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());
		}
	}
}

猜你喜欢

转载自czj4451.iteye.com/blog/1846555