[Pemrogaman]Membuat laporan menggunakan Dynamic Report


Hello hello kali ini saya (baca : mas bagus) akan membagi tutorial membuat laporan menggunakan Dynamic Report,tutorial ini sengaja dibuat sebagai referensi rekan saya yang sedang skripsi dan case nya menggunakan Dynamic Report ,ok lanjut saja

Requirement :
——————————

Langkah pertama kita membikin user interfacenya sebagai berikut :

*beri nama kelas jframe dengan : FormLaporan.java

Langkah kedua Buatlah :
-Database dengan nama : Laporan
-Tabel dengan nama : mahasiswa
-Isi field sebagai berikut :
1. nim varchar(9) (Primary Key)
2. nama varchar(30)
3. tgl_daftar date

* untuk praktisnya silahkan download database disini

Langkah ketiga
Extrack Dynamic Report yang telah anda download.

Langkah keempat
Tambahkan semua file dengan format .jar yang ada pada folder lib dan dist yang ada pada folder Dynamic Report ke library project yang telah anda buat.
Caranya pada Libraries yang ada pada project klik kanan -> Add JAR/Folder -> cari file .jar yang ada pada folder lib dan dist.

Langkah kelima
Tambahkan Library MySQL JDBC Driver ke library yang ada pada project.
Caranya pada Libraries yang ada pada project klik kanan -> Add Library -> cari library MySQL JDBC Driver.
Setelah file .jar dan MySQL JDBC Driver ditambahkan, tampilannya akan seperti ini

Langkah keenam
Pada project buat sebuah package dengan nama “net.sf.dynamicreports.examples“
caranya pada Source Packages klik kanan -> New -> Java Packages.

Langkah ketujuh
Pada package “net.sf.dynamicreports.examples” buat sebuah class dengan nama Templates
caranya : pada package “net.sf.dynamicreports.examples” klik kanan -> new -> Java Class

pada class Templates.java tulis syntax berikut


package net.sf.dynamicreports.examples;

/**
 *
 * @author baguza
 */
import java.awt.Color;
import java.util.Locale;
import net.sf.dynamicreports.report.base.expression.AbstractValueFormatter;
import static net.sf.dynamicreports.report.builder.DynamicReports.*;
import net.sf.dynamicreports.report.builder.HyperLinkBuilder;
import net.sf.dynamicreports.report.builder.ReportTemplateBuilder;
import net.sf.dynamicreports.report.builder.component.ComponentBuilder;
import net.sf.dynamicreports.report.builder.datatype.BigDecimalType;
import net.sf.dynamicreports.report.builder.style.StyleBuilder;
import net.sf.dynamicreports.report.builder.tableofcontents.TableOfContentsCustomizerBuilder;
import net.sf.dynamicreports.report.constant.HorizontalAlignment;
import net.sf.dynamicreports.report.constant.VerticalAlignment;
import net.sf.dynamicreports.report.definition.ReportParameters;

public class Templates {
	public static final StyleBuilder rootStyle;
	public static final StyleBuilder boldStyle;
	public static final StyleBuilder italicStyle;
	public static final StyleBuilder boldCenteredStyle;
	public static final StyleBuilder bold12CenteredStyle;
	public static final StyleBuilder bold18CenteredStyle;
	public static final StyleBuilder bold22CenteredStyle;
	public static final StyleBuilder columnStyle;
	public static final StyleBuilder columnTitleStyle;
	public static final StyleBuilder groupStyle;
	public static final StyleBuilder subtotalStyle;

	public static final ReportTemplateBuilder reportTemplate;
	public static final CurrencyType currencyType;
	public static final ComponentBuilder dynamicReportsComponent;
	public static final ComponentBuilder footerComponent;

	static {
		rootStyle           = stl.style().setPadding(2);
		boldStyle           = stl.style(rootStyle).bold();
		italicStyle         = stl.style(rootStyle).italic();
		boldCenteredStyle   = stl.style(boldStyle)
		                         .setAlignment(HorizontalAlignment.CENTER, VerticalAlignment.MIDDLE);
		bold12CenteredStyle = stl.style(boldCenteredStyle)
		                         .setFontSize(12);
		bold18CenteredStyle = stl.style(boldCenteredStyle)
		                         .setFontSize(18);
		bold22CenteredStyle = stl.style(boldCenteredStyle)
                             .setFontSize(22);
		columnStyle         = stl.style(rootStyle).setVerticalAlignment(VerticalAlignment.MIDDLE);
		columnTitleStyle    = stl.style(columnStyle)
		                         .setBorder(stl.pen1Point())
		                         .setHorizontalAlignment(HorizontalAlignment.CENTER)
		                         .setBackgroundColor(Color.LIGHT_GRAY)
		                         .bold();
		groupStyle          = stl.style(boldStyle)
		                         .setHorizontalAlignment(HorizontalAlignment.LEFT);
		subtotalStyle       = stl.style(boldStyle)
		                         .setTopBorder(stl.pen1Point());

		StyleBuilder crosstabGroupStyle      = stl.style(columnTitleStyle);
		StyleBuilder crosstabGroupTotalStyle = stl.style(columnTitleStyle)
		                                          .setBackgroundColor(new Color(170, 170, 170));
		StyleBuilder crosstabGrandTotalStyle = stl.style(columnTitleStyle)
		                                          .setBackgroundColor(new Color(140, 140, 140));
		StyleBuilder crosstabCellStyle       = stl.style(columnStyle)
		                                          .setBorder(stl.pen1Point());

		TableOfContentsCustomizerBuilder tableOfContentsCustomizer = tableOfContentsCustomizer()
			.setHeadingStyle(0, stl.style(rootStyle).bold());

		reportTemplate = template()
		                   .setLocale(Locale.ENGLISH)
		                   .setColumnStyle(columnStyle)
		                   .setColumnTitleStyle(columnTitleStyle)
		                   .setGroupStyle(groupStyle)
		                   .setGroupTitleStyle(groupStyle)
		                   .setSubtotalStyle(subtotalStyle)
		                   .highlightDetailEvenRows()
		                   .crosstabHighlightEvenRows()
		                   .setCrosstabGroupStyle(crosstabGroupStyle)
		                   .setCrosstabGroupTotalStyle(crosstabGroupTotalStyle)
		                   .setCrosstabGrandTotalStyle(crosstabGrandTotalStyle)
		                   .setCrosstabCellStyle(crosstabCellStyle)
		                   .setTableOfContentsCustomizer(tableOfContentsCustomizer);

		currencyType = new CurrencyType();

		HyperLinkBuilder link = hyperLink("http://dynamicreports.sourceforge.net");
		dynamicReportsComponent =
		  cmp.horizontalList(
		  	cmp.image(Templates.class.getResource("images/dynamicreports.png")).setFixedDimension(60, 60),
		  	cmp.verticalList(
		  		cmp.text("DynamicReports").setStyle(bold22CenteredStyle).setHorizontalAlignment(HorizontalAlignment.LEFT),
		  		cmp.text("http://dynamicreports.sourceforge.net").setStyle(italicStyle).setHyperLink(link)));

		footerComponent = cmp.pageXofY()
		                     .setStyle(
		                     	stl.style(boldCenteredStyle)
		                     	   .setTopBorder(stl.pen1Point()));
	}

	/**
	 * Creates custom component which is possible to add to any report band component
	 */
	public static ComponentBuilder createTitleComponent(String label) {
		return cmp.horizontalList()
		        .add(
		        	dynamicReportsComponent,
		        	cmp.text(label).setStyle(bold18CenteredStyle).setHorizontalAlignment(HorizontalAlignment.RIGHT))
		        .newRow()
		        .add(cmp.line())
		        .newRow()
		        .add(cmp.verticalGap(10));
	}

	public static CurrencyValueFormatter createCurrencyValueFormatter(String label) {
		return new CurrencyValueFormatter(label);
	}

	public static class CurrencyType extends BigDecimalType {
		private static final long serialVersionUID = 1L;

		@Override
		public String getPattern() {
			return "$ #,###.00";
		}
	}

	private static class CurrencyValueFormatter extends AbstractValueFormatter {
		private static final long serialVersionUID = 1L;

		private String label;

		public CurrencyValueFormatter(String label) {
			this.label = label;
		}

		public String format(Number value, ReportParameters reportParameters) {
			return label + currencyType.valueToString(value, reportParameters.getLocale());
		}
	}
}

Download file ini

Pada class laporan.java Tulis syntax berikut :


package demodynamicreport;

/**
 *
 * @author baguza
 */

import java.sql.*;
import javax.swing.table.DefaultTableModel;
import net.sf.dynamicreports.examples.Templates;
import net.sf.dynamicreports.jasper.builder.export.JasperXlsExporterBuilder;
import net.sf.dynamicreports.jasper.constant.JasperProperty;
import static net.sf.dynamicreports.report.builder.DynamicReports.*;
import net.sf.dynamicreports.report.builder.column.TextColumnBuilder;
import net.sf.dynamicreports.report.datasource.DRDataSource;
import net.sf.dynamicreports.report.exception.DRException;
import net.sf.jasperreports.engine.JRDataSource;

public class FormLaporan extends javax.swing.JFrame {
    int baris = 0;
    static Object kolom[] = {" I D ","       Nama       ","Tanggal Daftar"} ;
    DefaultTableModel mdl = new DefaultTableModel(kolom,baris);
    private String nim,nama;
    private Date tglDaftar; 

    public FormLaporan() {
        initComponents();
        isiTable();
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {

        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        jLabel1 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jButton1.setText("Laporan JTable");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jButton2.setText("laporan Database");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        jScrollPane1.setViewportView(jTable1);

        jLabel1.setText("//newbieilmu.wordpress.com");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jScrollPane1))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(25, 25, 25)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel1)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 162, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jButton2)))
                        .addGap(0, 0, Short.MAX_VALUE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 275, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton1)
                    .addComponent(jButton2))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 22, Short.MAX_VALUE)
                .addComponent(jLabel1)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>                        

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
try {
			JasperXlsExporterBuilder xlsExporter = export.xlsExporter("laporan.xls") // membuat laporan excel dengan nama "laporan.xls"
			                                             .setDetectCellType(true)
			                                             .setIgnorePageMargins(true)
			                                             .setWhitePageBackground(false)
			                                             .setRemoveEmptySpaceBetweenColumns(true);

			TextColumnBuilder itemColumn = col.column("I D", "nim", type.stringType())// membuat kolom pertama dengan label NIM, yang mengambil data dari datasource nim
			                                          .setFixedWidth(30)
			                                          .setStretchWithOverflow(false)
			                                          .addProperty(JasperProperty.PRINT_KEEP_FULL_TEXT, "true");

			report()
			  .setColumnTitleStyle(Templates.columnTitleStyle)
			  .addProperty(JasperProperty.EXPORT_XLS_FREEZE_ROW, "2")
			  .ignorePageWidth()
			  .ignorePagination()
			  .columns(
			  	itemColumn,
			  	col.column("Nama",   "nama",  type.stringType()).setFixedWidth(200),// menambah kolom ke-2, dengan label Nama yang mengambil data dari datasource nama
			  	col.column("Tanggal Daftar", "tgl_daftar", type.dateType()).setFixedWidth(250))// menambah kolom ke-3, dengan label Tanggal Daftar yang mengambil data dari datasource tanggalDaftar
                          .title(cmp.text("").setStyle(Templates.bold12CenteredStyle))// memberi jarak
                          .title(cmp.text("").setStyle(Templates.bold12CenteredStyle))// memberi jarak
                          .title(cmp.text("LAPORAN DATA MAHASISWA").setStyle(Templates.bold12CenteredStyle)) // menulis judul
                          .title(cmp.text("").setStyle(Templates.bold12CenteredStyle)) // memberi jarak
			  .setDataSource(createDataSourceTable())// mengambil data dari metode createDataSourceTable
			  .toXls(xlsExporter); // mengkonversi laporan jadi excel
		} catch (DRException e) {
			e.printStackTrace();
		}       

    }                                        

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
     try {  // keterangan sama dengan diatas
			JasperXlsExporterBuilder xlsExporter = export.xlsExporter("laporan.xls")
			                                             .setDetectCellType(true)
			                                             .setIgnorePageMargins(true)
			                                             .setWhitePageBackground(false)
			                                             .setRemoveEmptySpaceBetweenColumns(true);

			TextColumnBuilder itemColumn = col.column("I D", "nim", type.stringType())
			                                          .setFixedWidth(30)
			                                          .setStretchWithOverflow(false)
			                                          .addProperty(JasperProperty.PRINT_KEEP_FULL_TEXT, "true");

			report()
			  .setColumnTitleStyle(Templates.columnTitleStyle)
			  .addProperty(JasperProperty.EXPORT_XLS_FREEZE_ROW, "2")
			  .ignorePageWidth()
			  .ignorePagination()
			  .columns(
			  	itemColumn,
			  	col.column("Nama",   "nama",  type.stringType()).setFixedWidth(200),
			  	col.column("Tanggal Daftar", "tgl_daftar", type.dateType()).setFixedWidth(250))
                          .title(cmp.text("").setStyle(Templates.bold12CenteredStyle))
                          .title(cmp.text("").setStyle(Templates.bold12CenteredStyle))
                          .title(cmp.text("LAPORAN DATA MAHASISWA").setStyle(Templates.bold12CenteredStyle))
                          .title(cmp.text("").setStyle(Templates.bold12CenteredStyle))
			  .setDataSource(createDataSourceDatabase())
			  .toXls(xlsExporter);
		} catch (DRException e) {
			e.printStackTrace();
		}   // TODO add your handling code here:
    }                                        

    private void isiTable() { // untuk memngambil data dari database ke jtable
        try {
            // Setting Driver MySQL
            Class.forName("com.mysql.jdbc.Driver") ;
            // Buat Connection cn
            Connection cn = DriverManager.getConnection("jdbc:mysql:" +
            "///laporan","root","root");
            Statement smt = cn.createStatement();
            ResultSet rs = smt.executeQuery("select * from mahasiswa order by nim");
            while (rs.next()){
                  mdl.addRow(new Object[]{
                  rs.getString("nim"),
                  rs.getString("nama"),
                  rs.getDate("tgl_daftar")
                });
            }
            jTable1.setModel(mdl);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }private JRDataSource createDataSourceTable() { // mengambil data dari jtable, untuk dimasukkan ke laporan
	DRDataSource dataSource = new DRDataSource("nim", "nama", "tgl_daftar");//membuat datasource yang akan dijadikan "variabel name" kolom pada laporan
	int jumlahBaris = jTable1.getRowCount()-1; // mengetahui jumlah kolom pada jtable
        for ( int i=0;i<=jumlahBaris;i++) {
            nim = (String)mdl.getValueAt(i,0);
            nama= (String)mdl.getValueAt(i, 1);
            tglDaftar = (Date) mdl.getValueAt(i, 2);
            dataSource.add(nim,nama,tglDaftar); // mengisi datasource dari data jtable
        }
        return dataSource; // mengirim nilai datasource
    } private JRDataSource createDataSourceDatabase() { // mengambil data dari database, untuk dimasukkan ke laporan
	DRDataSource dataSource = new DRDataSource("nim", "nama", "tgl_daftar");//membuat datasource yang akan dijadikan "variabel name" kolom pada laporan
	try {
            // Setting Driver MySQL
            Class.forName("com.mysql.jdbc.Driver") ;
            // Buat Connection cn
            Connection cn = DriverManager.getConnection("jdbc:mysql:" +
            "///laporan","root","root");
            Statement smt = cn.createStatement();
            ResultSet rs = smt.executeQuery("select * from mahasiswa order by nim");
            while (rs.next()){
                  nim = rs.getString("nim");
                  nama = rs.getString("nama");
                  tglDaftar = rs.getDate("tgl_daftar");
                  dataSource.add(nim,nama,tglDaftar); // mengisi datasource dari data database
            }

        } catch (ClassNotFoundException | SQLException e) {
            e.printStackTrace();
        }
        return dataSource; // mengirim nilai datasource
    }

    public static void main(String args[]) {
        /*
         * Set the Nimbus look and feel
         */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /*
         * If Nimbus (introduced in Java SE 6) is not available, stay with the
         * default look and feel. For details see
         * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(FormLaporan.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(FormLaporan.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(FormLaporan.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(FormLaporan.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /*
         * Create and display the form
         */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new FormLaporan().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTable1;
    // End of variables declaration
}

Download file ini

nah setelah di compile maka akan muncul view berikut

Silahkan buka file Laporan di folder project yang kalian buat.
maka akan otomatis muncul file dengan berkas laporan.xls seperti berikut :


Notes :

  • Pastikan database kalian sama
  • Pastikan username & password nya di samakan dengan setting mysql anda (defaultnya username : root,password : root )
  • jika masih error mohon di koreksi kembali biasanya koneksi ke database nya yang error

Semoga bermanfaat tutorial ini🙂

referensi : http://zonapedia.wordpress.com/2012/06/01/j2se-membuat-laporan-sederhana-menggunakan-dynamic-report/

Founder Tamyiz Soft

Anugrah Bagus Susilo

9 pemikiran pada “[Pemrogaman]Membuat laporan menggunakan Dynamic Report

  1. kalau ditampilkan reportnya sebagai chart, jadinya file xls juga?😀

  2. bisa yah bisa tidak tergantung kebutuhahan,kalo perlu yah di tampilkan kalo tidak ya tidak,sbenernya sih ada jfreechart kalo buat report pake itu lebih enak,mungkin saya posting lain kali hehe
    http://www.jfree.org/jfreechart/

  3. kerennn makasih yah..gan

  4. import static net.sf.dynamicreports.report.builder.DynamicReports.*;
    import net.sf.dynamicreports.report.builder.HyperLinkBuilder;
    import net.sf.dynamicreports.report.builder.ReportTemplateBuilder;
    import net.sf.dynamicreports.report.builder.component.ComponentBuilder;
    import net.sf.dynamicreports.report.builder.datatype.BigDecimalType;
    import net.sf.dynamicreports.report.builder.style.StyleBuilder;
    import net.sf.dynamicreports.report.builder.tableofcontents.TableOfContentsCustomizerBuilder;
    import net.sf.dynamicreports.report.constant.HorizontalAlignment;
    import net.sf.dynamicreports.report.constant.VerticalAlignment;
    import net.sf.dynamicreports.report.definition.ReportParameters;

    *******
    package ini ambil dari mana gan?
    klu bisa tlng krim listingnya gan. thx

  5. gan ko error
    Exception in thread “AWT-EventQueue-0” java.lang.NoClassDefFoundError: org/apache/commons/lang3/Validate
    at net.sf.dynamicreports.jasper.base.export.AbstractJasperExporter.setOutputFileName(AbstractJasperExporter.java:88)
    at net.sf.dynamicreports.jasper.builder.export.AbstractJasperExporterBuilder.setOutputFileName(AbstractJasperExporterBuilder.java:60)
    at net.sf.dynamicreports.jasper.builder.export.Exporters.xlsExporter(Exporters.java:254)
    at net.sf.dynamicreports.jasper.builder.export.ExporterBuilders.xlsExporter(ExporterBuilders.java:255)

  6. Sungguh membantu, Kang. Terima kasih banyak.

Tinggalkan Balasan

Isikan data di bawah atau klik salah satu ikon untuk log in:

Logo WordPress.com

You are commenting using your WordPress.com account. Logout / Ubah )

Gambar Twitter

You are commenting using your Twitter account. Logout / Ubah )

Foto Facebook

You are commenting using your Facebook account. Logout / Ubah )

Foto Google+

You are commenting using your Google+ account. Logout / Ubah )

Connecting to %s