介绍
本文介绍报表工具JasperReport。
示例
[codesyntax lang="java"]
package org.suren.demo.jasperreport;标签:java,String,JRException,JasperReport,new,import,throws From: https://blog.51cto.com/suren/5761246
import java.awt.Desktop;
import java.io.File;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.HashMap;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperFillManager;
import org.junit.BeforeClass;
/**
* JasperReport测试</br>
* 本demo使用MySQL作为数据源,填充到JasperReport模板中,最后导出报表。
* @author suren
* @date 2016年8月26日 下午5:18:39
*/
public class JasperReportTest
{
/** 填充后的数据文件路径 */
private static String jrprintPath;
/**
* 向模板中填充数据
* @throws Exception
*/
@BeforeClass
public static void fill() throws Exception
{
File reportFile = new File("MyReports", "Blank_A4.jasper");
jrprintPath = JasperFillManager.fillReportToFile(
reportFile.getAbsolutePath(),
new HashMap<String, Object>(),
getDemoConnection()
);
System.out.println(jrprintPath);
}
/**
* 导出html格式报表
* @throws Exception
*/
@org.junit.Test
public void htmlExport() throws Exception
{
String htmlPath = JasperExportManager.exportReportToHtmlFile(jrprintPath);
System.out.println(htmlPath);
Desktop.getDesktop().open(new File(htmlPath));
}
/**
* 数据库连接
* @return
* @throws JRException
*/
private static Connection getDemoConnection() throws JRException
{
Connection conn;
try
{
String driver = "com.mysql.jdbc.Driver";
String connectString = "jdbc:mysql://localhost/surenpi";
String user = "root";
String password = "root";
Class.forName(driver);
conn = DriverManager.getConnection(connectString, user, password);
}
catch (ClassNotFoundException e)
{
throw new JRException(e);
}
catch (SQLException e)
{
throw new JRException(e);
}
return conn;
}
}
[/codesyntax]