前言
前面的几篇我们讲解的都是一些普通简单格式的报表,但是有时我们的报表会要求是表格形式的,这时我们就需要用到我们的JRTableModelDataSource。
正题
跟之前的一样,我们要生成报表需要以下几个步骤:
1.引入jar包,请看《静态文本报表》 。
2.新建报表模版:
跟我们前一篇的AircraftReport报表模版是一样的,请参见《不同数据源之Map数据源》;
3.编译报表模版,请看《静态文本报表》。
4.编写servlet:
package com.dan.jasper; import java.awt.BorderLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.HashMap; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JTable; import javax.swing.table.DefaultTableModel; import net.sf.jasperreports.engine.JRException; import net.sf.jasperreports.engine.JasperFillManager; import net.sf.jasperreports.engine.JasperPrint; import net.sf.jasperreports.engine.data.JRTableModelDataSource; import net.sf.jasperreports.view.JasperViewer; public class TableModelReport { JFrame mainFrame; BorderLayout borderLayout; DefaultTableModel tableModel; JTable table = new JTable(); JButton generateReportButton = new JButton("Generate Report"); public TableModelReport(){ mainFrame = new JFrame("Aircraft Data"); borderLayout = new BorderLayout(); generateReportButton.addActionListener(new ReportGenerator()); populateTableModel(); mainFrame.setSize(640, 150); mainFrame.setVisible(true); mainFrame.getContentPane().setLayout(borderLayout); mainFrame.add(new JLabel("Aircraft Data"),BorderLayout.NORTH); table.setModel(tableModel); mainFrame.getContentPane().add(table,BorderLayout.CENTER); mainFrame.getContentPane().add(generateReportButton, BorderLayout.SOUTH); mainFrame.setVisible(true); } private void populateTableModel(){ String[] columnNames = {"ID","NAME","SEX"}; String[][] data = { {"1","Rebecca1","female"}, {"2","Rebecca2","female"}, {"3","Rebecca3","female"}, {"4","Rebecca4","female"} }; tableModel = new DefaultTableModel(data, columnNames); } private void displayReport(){ JasperPrint jasperPrint = generateReport(); JasperViewer jasperViewer = new JasperViewer(jasperPrint); jasperViewer.setVisible(true); } private JasperPrint generateReport(){ JasperPrint jasperPrint = null; try{ jasperPrint = JasperFillManager.fillReport("E:/Project/Work1/Report3/WebRoot/WEB-INF/classes/reports/AircraftReport.jasper", new HashMap(),new JRTableModelDataSource(tableModel)); }catch(JRException e){ e.printStackTrace(); } return jasperPrint; } private class ReportGenerator implements ActionListener{ public void actionPerformed(ActionEvent e){ displayReport(); } } public static void main(String[] args){ new TableModelReport(); } }
5.配置web.xml,就是配置servlet
6.运行项目
看一下我的运行结果:
小结:
这个表格形式的报表跟我们最前面的预览报表很像,只不过它展现了表格的样式而且还要预览打印报表的功能。