Report In Java – Step 1


Hôm nay mình sẻ hướng dẫn các bạn tạo Report trong java sử dụng DynamicReport cùng với database .

Các thư viện chúng ta cần chuẩn bị :

DynamicReport 3.x

JasperReports 5.x

Driver Connector MySQL 5.x

Các bạn có thể down DynamicReports từ [Click Here] . Trong bài viết này mình sử dụng Maven để download các file jar cần thiết chúng ta add vào file porm.xml của chúng ta như sau :

                <dependency>
			<groupId>net.sourceforge.dynamicreports</groupId>
			<artifactId>dynamicreports-core</artifactId>
			<version>3.1.3</version>
		</dependency>

		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>5.1.25</version>
		</dependency>

Ok bước qua phần cấu hình chúng ta tạo database với table như sau :
d1

Và nhập 1 vài mẩu tin : ví dụ như hình :
d1

Tạo 1 class Connect Database đơn giản như sau :

package thaihoanghai.wordpress.com.demo;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
/**
 * This class used : open/close Connect to DB and create Query
 * @author kobe
 */
public class ConnectDB {

	Connection connect = null;
	Statement stmt = null;
	ResultSet rs = null;

	/**
	 * Check Driver connect to MySQL
	 */
	protected void hasDriver() throws Exception{
		try {
			Class.forName("com.mysql.jdbc.Driver");
		} catch (ClassNotFoundException ex) {
			throw new Exception ("Invalid Driver!!Please check this drver....");
		}
	}

	/**
	 * Function used to get the connection to the Database
	 * Step 1 - I check my connection or not!!
	 * Step 2 - If not, it will be null and initialization.
	 * Step 3 - Then it return
	 * @return Connection
	 */
	protected Connection openConnect() throws Exception{
		if(connect == null){
			hasDriver();
			String url = "jdbc:mysql://localhost/dbtest";
			try {
				this.connect = DriverManager.getConnection(url,"root","123456");
			} catch (SQLException e) {
				throw new Exception(e.getMessage() + "Connect failed to database .... ");
			}
		}
		return connect;
	}
	/**
	 * Make a Statement to execute the SQL statement
	 * @return Statement
	 */
	protected Statement getStatement() throws SQLException, Exception{
		if(stmt == null){
			stmt = openConnect().createStatement();
		}
		return stmt;
	}

	/**
	 * Used to execute the Insert, Update, Delete statement
	 * @param strSQL Query VD: Insert into TableName values ('??','??')
	 * @return The number of lines affected by the command
	 */
	public int executeUpdate(String strSQL) throws Exception{
		int result = 0;
		try {
			result = getStatement().executeUpdate(strSQL);
		} catch (Exception ex) {
			throw new Exception(ex.getMessage() + " Error at: " + strSQL);
		}finally{
			this.closeConnet();
		}
		return result;
	}

	public ResultSet executeQuery(String strSQL) throws Exception{
		try {
			rs = getStatement().executeQuery(strSQL);
		} catch (Exception e) {
			throw new Exception(e.getMessage() +" Error at : " + strSQL);
		}
		return rs;
	}

	/**
	 * A method to close the connection.
	 * @throws SQLException
	 */
	public void closeConnet() throws SQLException{
		if(rs != null && !rs.isClosed())
			rs.close();
		if(stmt != null)
			stmt.close();
		if(connect != null)
			connect.close();
	}

}

Chúng Ta thiết lập hàm main như sau :

package thaihoanghai.wordpress.com.demo;

import java.io.FileOutputStream;

import net.sf.dynamicreports.jasper.builder.JasperReportBuilder;
import net.sf.dynamicreports.report.builder.DynamicReports;
import net.sf.dynamicreports.report.builder.column.Columns;
import net.sf.dynamicreports.report.builder.component.Components;
import net.sf.dynamicreports.report.builder.datatype.DataTypes;
import net.sf.dynamicreports.report.constant.HorizontalAlignment;

/**
 * Hello world!
 *
 */
public class App
{
    public static void main( String[] args ) throws Exception
    {
    	ConnectDB connect = new ConnectDB();
    	// Create new report design
		JasperReportBuilder report = DynamicReports.report();
		report.columns(// add columns
				// Column (Title, Field_Name_From_Database, Data Type)
				Columns.column("ID Person","id",DataTypes.stringType()),
				Columns.column("Full Name", "name", DataTypes.stringType()),
				Columns.column("Address", "address", DataTypes.stringType()),
				Columns.column("BirthDay", "birthday", DataTypes.stringType()))
		.title(Components.text("Simple Report")// Show Report title
			   .setHorizontalAlignment(HorizontalAlignment.CENTER))// Set position for title
		.pageFooter(Components.pageXofY()) // show number of page at page footer
		// set datasource with specific query from database
		.setDataSource("select id, name, address, birthday from person",connect.openConnect());

		try {
			report.show();
			report.toPdf(new FileOutputStream("d:/report.pdf"));
		} catch (Exception e) {
			e.printStackTrace();
		}
    }
}

Kết quả sau khi run:

Show với JasperViewer

d1

File report.pdf

d1

Chúc các bạn thành công

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: