jasperreport
项目截图如下:
该项目是:Maven项目
pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>JasperReports</groupId>
<artifactId>JasperReports</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>JasperReports Maven WebAPP</name>
<url>http://maven.apache.org</url>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<!-- ireport JasperReports -->
<dependency>
<groupId>net.sf.jasperreports</groupId>
<artifactId>jasperreports</artifactId>
<version>5.6.0</version>
</dependency>
<dependency>
<groupId>org.codehaus.groovy</groupId>
<artifactId>groovy-all</artifactId>
<version>2.2.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.30</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.14</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.14</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml-schemas</artifactId>
<version>3.14</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.itextpdf/itext-asian -->
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itext-asian</artifactId>
<version>5.1.0</version>
</dependency>
<!-- 解决pdf中文问题 导入jar包 开始 -->
<!-- https://mvnrepository.com/artifact/net.sourceforge.javydreamercsw/JasperReport -->
<dependency>
<groupId>net.sourceforge.javydreamercsw</groupId>
<artifactId>JasperReport</artifactId>
<version>0.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.jaspersoft/ireport -->
<dependency>
<groupId>com.jaspersoft</groupId>
<artifactId>ireport</artifactId>
<version>1.0.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.itextpdf/itextpdf -->
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itextpdf</artifactId>
<version>5.1.0</version>
</dependency>
<!-- 解决pdf中文问题 导入jar包 结束 -->
</dependencies>
<build>
<finalName>JasperReports</finalName>
</build>
</project>
DbReport.jrxml 如下:
<?xml version="1.0" encoding="UTF-8" ?>
<jasperReport xmlns="http://jasperreports.sourceforge.net/jasperreports"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://jasperreports.sourceforge.net/jasperreports
http://jasperreports.sourceforge.net/xsd/jasperreport.xsd" name="DbReport" >
<!-- jasperReport标签中name="DbReport"需要对应外面文件名, $P{}为填充参数,$V{}为值 ,$F{}为查询值或者为Jr数据-->
<!-- 页面样式标签 属性:
forecolor(前景色,就是文本)
backcolor(背景色)
hAlign(水平位置Center, Justified, Left, Right)
vAlign(垂直位置Bottom, Middle, Top)
border(边框1Point, 2Point, 4Point, Dotted, None, Thin)
borderColor(边框颜色)
fontName(字体)
fontSize(字体大小)
isBold,isItalic,IsUnderline,isStrikeThrough(粗体,斜体,下画线,..)
lineSpacing(1_1_2, Double, Single行间距)
rotation(旋转,Left, None, Right,转的是90度)
isStyledText(指示这个Element是否用Style,true,false)
isDefault(说明这个样式是否默认样式)
-->
<style name="pageHeader" forecolor="#FFFFFF" backcolor="#333333" />
<!--<style name="pdfStyle" isDefault="true" pdfFontName="STSong-Light" pdfEncoding="UniGB-UCS2-H(Chinese Siplified)" isPdfEmbedded="true"/> -->
<!-- 参数标签 -->
<parameter name="name" class="java.lang.String"/>
<!-- 查询语句标签 -->
<queryString>
<![CDATA[
select id,age,name from user where name=$P{name}
]]>
</queryString>
<!-- 显示字段标签 -->
<field name="id" class="java.lang.integer" />
<field name="name" class="java.lang.String" />
<field name="age" class="java.lang.String" />
<pageHeader>
<band height="30">
<staticText>
<reportElement style="pageHeader" x="0" y="5" width="55" height="15"/>
<textElement textAlignment="Center"/>
<text><![CDATA[ID]]></text>
</staticText>
<staticText>
<reportElement style="pageHeader" x="55" y="5" width="205" height="15"/>
<text><![CDATA[Name]]></text>
</staticText>
<staticText>
<reportElement style="pageHeader" x="160" y="5" width="255" height="15"/>
<text><![CDATA[Age]]></text>
</staticText>
</band>
</pageHeader>
<!-- 显示内容-->
<detail>
<band height="20">
<textField>
<reportElement x="0" y="4" width="50" height="15"/>
<textElement textAlignment="Right"/>
<textFieldExpression><![CDATA[$F{id}]]></textFieldExpression>
</textField>
<textField isStretchWithOverflow="true">
<reportElement positionType="Float" x="55" y="4" width="100" height="15"/>
<textFieldExpression><![CDATA[$F{name}]]></textFieldExpression>
</textField>
<textField isStretchWithOverflow="true">
<reportElement positionType="Float" x="160" y="4" width="100" height="15"/>
<textFieldExpression><![CDATA[$F{age}]]></textFieldExpression>
</textField>
<line>
<reportElement positionType="Float" x="0" y="19" width="515" height="1" forecolor="#808080"/>
</line>
</band>
</detail>
</jasperReport>
Jdbc.java 如下:
package com.accord.dao;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.statement;
public class Jdbc {
public static String driver="com.mysql.jdbc.Driver";
public static String url="jdbc:mysql://localhost:3306/db_studentinfo";
public static String user="root";
public static String pwd="123456";
public static Connection conn= getConnection();
public static Statement statement= getStatement();
public static Connection getConnection(){
if(conn==null){
try{
class.forname(driver);
conn=DriverManager.getConnection(url,user,pwd);
}catch(Exception e){
e.printstacktrace();
}
}
return conn;
}
private static Statement getStatement(){
if(statement==null){
try{
statement=conn.createStatement();
}catch(Exception e){
e.printStackTrace();
}
}
return statement;
}
public static ResultSet getResultSet(String sql){
ResultSet rs=null;
try{
rs=statement.executequery(sql);
}catch(Exception e){
e.printStackTrace();
}
return rs;
}
public static void closeAll(ResultSet rs,Statement st,Connection cn){
try{
if(rs!=null){
rs.close();
}
if(st!=null){
st.close();
}
if(cn!=null){
cn.close();
}
}catch(Exception e){
e.printStackTrace();
}
}
}
创建一个Servlet,TestHttpReportServlet.java 如下:
package com.accord.test;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.Servletcontext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletrequest;
import javax.servlet.http.HttpServletresponse;
import net.sf.jasperreports.engine.JRdatasource;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JRExporterParameter;
import net.sf.jasperreports.engine.JRruntimeexception;
import net.sf.jasperreports.engine.JasperCompileManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.engine.data.JRMapArrayDataSource;
import net.sf.jasperreports.engine.export.JRHtmlExporter;
import net.sf.jasperreports.engine.export.JRPdfExporter;
import net.sf.jasperreports.engine.export.JRXlsExporter;
import net.sf.jasperreports.engine.export.JRXlsExporterParameter;
import net.sf.jasperreports.engine.util.JRLoader;
import com.accord.dao.Jdbc;
public class TestHttpReportServlet extends HttpServlet {
public static void main(String[] args) {
String path = "http://localhost:8080/JasperReports/TestHttpReportServlet";
String str = path.substring(0, path.lastindexof("/"));
System.out.println(str);
}
private static final long serialversionuid = 1L;
public TestHttpReportServlet() {
super();
}
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// System.out.println("1");
doPost(request, response);
}
@SuppressWarnings("deprecation")
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
ServletContext context = this.getServletConfig().getServletContext();
try {
//JasperCompileManager.compileReportToFile("E:/report/DbReport.jrxml");
JasperCompileManager.compileReportToFile(context.getrealpath("/reports/DbReport.jrxml"));
} catch (JRException e1) {
e1.printStackTrace();
}//编译jrxml文件,生成jasper文件
File reportFile = new File(context.getRealPath("/reports/DbReport.jasper"));
if (!reportFile.exists())
throw new JRRuntimeException("FilewebappReport.jasper "
+ "not found. The report design must be compiledfirst.");
Map map = new HashMap();
map.put("name", "张三");
try {
File jasperFile = new File(context.getRealPath("/reports/DbReport.jasper"));
JasperReport jasperReport = (JasperReport) JRLoader.loadObject(jasperFile);
JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, map, Jdbc.getConnection());
String fileName = jasperPrint.getName() + ".html";
File destFile = new File(context.getRealPath("/reports"), fileName);
String destFileName = destFile.toString();
//生成html数据
JRHtmlExporter exporter = new JRHtmlExporter();
exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
exporter.setParameter(JRExporterParameter.OUTPUT_FILE_NAME,destFileName);
exporter.setParameter(JRExporterParameter.CHARACTER_ENCODING,"gb2312"); // 关键是此句
exporter.exportReport();
System.out.println(request.getRequestURL());
String path = request.getRequestURL().toString();
String str = path.substring(0, path.lastIndexOf("/"));
response.sendredirect(str + "/reports/" + fileName);
//生成excel
/*JRXlsExporter xls = new JRXlsExporter();
xls.setParameter(JRXlsExporterParameter.JASPER_PRINT, jasperPrint);
xls.setParameter(JRXlsExporterParameter.OUTPUT_STREAM, response.getoutputstream());
xls.setParameter(JRXlsExporterParameter.IS_ONE_PAGE_PER_SHEET, Boolean.FALSE);
xls.setParameter(JRXlsExporterParameter.IS_WHITE_PAGE_BACKGROUND, Boolean.FALSE);
response.setheader("content-Disposition", "attachement;filename=first.xls");
response.setcontenttype("application/vnd_ms-excel");
xls.exportReport();*/
//生成pdf
/*JRPdfExporter pdf = new JRPdfExporter();
pdf.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
pdf.setParameter(JRExporterParameter.OUTPUT_STREAM, response.getOutputStream());
response.setHeader("Content-Disposition", "attachement;filename=first.pdf");
response.setContentType("application/pdf");
response.setCharacterEncoding("UTF-8");
pdf.exportReport();*/
} catch (JRException e) {
e.printStackTrace();
}
}
public JRDataSource getReportDataSource() {
JRMapArrayDataSource dataSource = new JRMapArrayDataSource(
getMaparray());
return dataSource;
}
public Map[] getMaparray() {
// map key键必须对应DbReport.jrxml中显示数据字段
Map map1 = new HashMap();
map1.put("id", 1);
map1.put("name", "aaa");
map1.put("age", "20");
Map map2 = new HashMap();
map2.put("id", 2);
map2.put("name", "bbb");
map2.put("age", "28");
Map map3 = new HashMap();
map3.put("id", 3);
map3.put("name", "ccc");
map3.put("age", "30");
Map[] mapArray = new Map[3];
mapArray[0] = map1;
mapArray[1] = map2;
mapArray[2] = map3;
return mapArray;
}
}
web.xml 如下:
<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD web application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd" >
<web-app>
<display-name>Archetype Created Web Application</display-name>
<servlet>
<servlet-name>TestHttpReportServlet</servlet-name>
<display-name>TestHttpReportServlet</display-name>
<description></description>
<servlet-class>com.accord.test.TestHttpReportServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>TestHttpReportServlet</servlet-name>
<url-pattern>/TestHttpReportServlet</url-pattern>
</servlet-mapping>
</web-app>
打开浏览器,访问链接地址:http://localhost:8080/JasperReports/TestHttpReportServlet
TestHttpReport.java 如下:
package com.accord.test;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.jasperreports.engine.JRDataSource;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JasperCompileManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.engine.JasperRunManager;
import net.sf.jasperreports.engine.data.JRMapArrayDataSource;
import net.sf.jasperreports.engine.export.JRXlsExporter;
import net.sf.jasperreports.engine.export.JRXlsExporterParameter;
import net.sf.jasperreports.engine.util.JRLoader;
import com.accord.dao.Jdbc;
@SuppressWarnings("serial")
public class TestHttpReport extends HttpServlet {
public void service(HttpServletRequest request,
HttpServletResponse response) {
try {
ServletContext context = this.getServletConfig().getServletContext();
//JasperCompileManager 编译管理器
//JasperFillManager 填充管理器
//JRXmlLoader xml加载器
//JasperPrintManager 打印管理器
//JasperExportManager 导出管理器
//JasperRunManager 运行管理器
//编译jrxml文件,生成jasper文件
JasperCompileManager.compileReportToFile(context.getRealPath("/reports/DbReport.jrxml"));
Map map = new HashMap();
map.put("name", "张三");
File jasperFile = new File(context.getRealPath("/reports/DbReport.jasper"));
JasperReport jasperReport = (JasperReport) JRLoader.loadObject(jasperFile);
JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, map, Jdbc.getConnection());
//以map数组位数据源,生成html文件
JasperRunManager.runReportToHtmlFile(context.getRealPath("/reports/DbReport.jasper"), "E:/report/test2.html", map, getReportDataSource());
try {
//生成excel
JRXlsExporter xls = new JRXlsExporter();
xls.setParameter(JRXlsExporterParameter.JASPER_PRINT, jasperPrint);
xls.setParameter(JRXlsExporterParameter.OUTPUT_STREAM, response.getOutputStream());
xls.setParameter(JRXlsExporterParameter.IS_ONE_PAGE_PER_SHEET, Boolean.FALSE);
xls.setParameter(JRXlsExporterParameter.IS_WHITE_PAGE_BACKGROUND, Boolean.FALSE);
response.setHeader("Content-Disposition", "attachment;filename=first.xls");
response.setContentType("application/vnd_ms-excel");
xls.exportReport();
} catch (IOException e) {
e.printStackTrace();
}
} catch (JRException e) {
e.printStackTrace();
}
}
public JRDataSource getReportDataSource() {
JRMapArrayDataSource dataSource = new JRMapArrayDataSource(getMaparray());
return dataSource;
}
public Map[] getMaparray() {
//map key键必须对应DbReport.jrxml中显示数据字段
Map map1=new HashMap();
map1.put("id", 1);
map1.put("name", "aaa");
map1.put("age", "20");
Map map2=new HashMap();
map2.put("id", 2);
map2.put("name", "bbb");
map2.put("age", "28");
Map map3=new HashMap();
map3.put("id", 3);
map3.put("name", "ccc");
map3.put("age", "30");
Map[] mapArray=new Map[3];
mapArray[0]=map1;
mapArray[1]=map2;
mapArray[2]=map3;
return mapArray;
}
}
TestJrxmlToJasper.java 如下:
package com.accord.test;
import java.io.File;
import java.io.fileinputstream;
import java.io.InputStream;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JasperCompileManager;
public class TestJrxmlToJasper {
public static void main(String[] args) throws Exception {
String path = "E:/report/DbReport.jrxml";
File file = new File(path);
String parentPath = file.getParent();
String jrxmlDestSourcePath = "E:/report/DbReport.jasper";
JasperCompileManager.compileReportToFile(path,
jrxmlDestSourcePath);
InputStream isRef = new FileInputStream(new File(jrxmlDestSourcePath));
/*ServletOutputStream sosRef = response.getOutputStream();
response.setContentType("application/pdf");
JasperRunManager.runReportToPdfStream(isRef,sosRef,new HashMap(),
new JRemptyDataSource());
sosRef.flush();
sosRef.close();*/
}
}
TestReport.java 如下:
package com.accord.test;
import java.io.File;
import java.util.HashMap;
import java.util.Map;
import com.accord.dao.Jdbc;
import net.sf.jasperreports.engine.JRExporterParameter;
import net.sf.jasperreports.engine.JasperCompileManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.engine.export.JRHtmlExporter;
import net.sf.jasperreports.engine.export.JRHtmlExporterParameter;
import net.sf.jasperreports.engine.export.JRXlsExporter;
import net.sf.jasperreports.engine.export.JRXlsExporterParameter;
import net.sf.jasperreports.engine.export.JRXmlExporterParameter;
import net.sf.jasperreports.engine.util.JRLoader;
public class TestReport {
public static void main(String[] args) {
service();
}
//protected void service(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {\
public static void service(){
try{
//ServletContext context = this.getServletConfig().getServletContext();
//JasperCompileManager 编译管理器
//JasperFillManager 填充管理器
//JRXmlLoader xml加载器
//JasperPrintManager 打印管理器
//JasperExportManager 导出管理器
JasperCompileManager.compileReportToFile("E:/report/DbReport.jrxml");//编译jrxml文件,生成jasper文件
Map map=new HashMap();//参数map
map.put("name", "张三");
//生成jrprint文件
//JasperFillManager.fillReportToFile(context.getRealPath("/reports/DbReport.jasper"), map, JDBC.conn);
File jasperFile=new File("E:/report/DbReport.jasper");
JasperReport jasperReport =(JasperReport)JRLoader.loadObject(jasperFile);
JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, map,Jdbc.getConnection());
File file=new File("E:/report/DbReport.html");
//生成html 测试成功
/*JRHtmlExporter html = new JRHtmlExporter();
html.setParameter(JRHtmlExporterParameter.JASPER_PRINT, jasperPrint);
html.setParameter(JRHtmlExporterParameter.OUTPUT_FILE_NAME,"E:/report/DbReport.html");//生成文件
//html.setParameter(JRHtmlExporterParameter.OUTPUT_WRITER,response.getWriter()); // web页面显示
html.setParameter(JRHtmlExporterParameter.IS_USING_IMAGES_TO_ALIGN,Boolean.FALSE);
html.setParameter(JRExporterParameter.CHARACTER_ENCODING, "utf-8");
html.exportReport();*/
//生成excel
/*JRXlsExporter xls=new JRXlsExporter();
xls.setParameter(JRXlsExporterParameter.JASPER_PRINT, jasperPrint);
xls.setParameter(JRXlsExporterParameter.OUTPUT_STREAM, respon);
xls.exportReport();*/
//生成pdf
/*
JRPdfExporter pdf = new JRPdfExporter();
*/
}catch(Exception e){
e.printStackTrace();
}
}
}
注:JasperReport 生成的Pdf文件,中文不显示,这个没有解决,路过的大神指点一下! [email protected]
相关阅读
Jasperreport基本介绍(Jasperreport与Ireport介绍)
Jasperreport基本介绍Jasperreport与Ireport介绍Jasperreport是报表打印工具,支持pdf、csv多种格式的报表打印。JasperReport是一