码迷,mamicode.com
首页 > Web开发 > 详细

EChart整合JasperReport在struts2环境中导出

时间:2016-04-29 13:59:34      阅读:187      评论:0      收藏:0      [点我收藏+]

标签:

EChart是百度前端团队开发的一个图表展示控件,功能很全,效果很炫,可以直接百度到各种教程和资源。

JasperReport是Java中处理报表的一种方式,配合iReport工具可以进行可视化的报表开发,也比较方便。

下面主要是一个小小的实例。

项目工程和jar包截图如下,其中jar包的截图是多于实际需要的jar的

技术分享

技术分享

技术分享

 

下面开始步骤讲解:

首先是前端的jsp显示:

echart_export.jsp

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%@ taglib prefix="s" uri="/struts-tags" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP ‘index.jsp‘ starting page</title>
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">    
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
    <!--
    <link rel="stylesheet" type="text/css" href="styles.css">
    -->
    <script src="common/js/jquery-1.9.1.js"></script>
    <script src="common/js/echarts.min.js"></script>
    
    <script type="text/javascript">
    
    var path;
    
    $(document).ready(function(){
         // 基于准备好的dom,初始化echarts实例
        var myChart = echarts.init(document.getElementById(main));
        // 使用刚指定的配置项和数据显示图表。
            myChart.setOption({
            series : [
                {
                    name: 访问来源,
                    type: pie,
                    radius: 55%,
                    //roseType: ‘angle‘,
                    data:[
                        {value:400, name:搜索引擎},
                        {value:335, name:直接访问},
                        {value:310, name:邮件营销},
                        {value:274, name:联盟广告},
                        {value:235, name:视频广告}
                    ]
                }
            ]
        });
        path = myChart.getDataURL("png");
    });
    
    function expEchart(){
        if(confirm("确定要导出清单?")){
            $.post("JasperAction_export.action",{imgsURl : path},function(vaa){
                if(vaa != undefined && vaa.indexOf("success") > -1){
                    alert("开始导出,路径:" + vaa.substring(8));
                    var url="JasperAction_echart.action?picUrl=" + vaa.substring(8);
                    location.href=url;
                    //window.open(url,‘exportReport‘,‘height=5,width=5,status=yes,toolbar=no,menubar=no,location=no‘);
                    //alert("导出成功");
                } else {
                    alert("导出异常:" + vaa);
                }
            });    
            
            
        }
    }
    </script>
  </head>
  
  <body>
    Ttest jasperreport<br> 
        <h1>echart test</h1>
        <!-- 为 ECharts 准备一个具备大小(宽高)的Dom -->
        <input type="button" value="导出" onclick="expEchart();"/>
    <div id="main" style="width: 600px;height:400px;"></div>
  </body>
</html>

 可以看到,关键点就是这句

path = myChart.getDataURL("png");

echart显示的图表默认是png格式,这句代码就是把显示的图表的二进制内容赋值给path

点击页面的导出按钮,会触发expEchart()方法,接着会触发一个post方式的ajax请求,注意post请求的参数,下面是JasperAction

  1 package com.yzj.action;
  2 
  3 import java.io.File;
  4 import java.io.FileOutputStream;
  5 import java.io.IOException;
  6 import java.io.OutputStream;
  7 import java.io.PrintWriter;
  8 import java.text.SimpleDateFormat;
  9 import java.util.Date;
 10 import java.util.HashMap;
 11 import java.util.LinkedList;
 12 import java.util.List;
 13 import java.util.Map;
 14 
 15 import javax.servlet.http.HttpServletResponse;
 16 
 17 import org.apache.struts2.ServletActionContext;
 18 
 19 import sun.misc.BASE64Decoder;
 20 
 21 import com.opensymphony.xwork2.ActionSupport;
 22 
 23 public class JasperAction extends ActionSupport{
 24 
 25     private List<User> list;
 26     private Map<String,String> reportParameters;
 27     private final Map<Object,Object> exportParameters=(Map<Object,Object>)JasperUtils.getMap();
 28     
 29     String imgsURl;
 30     String vaa;
 31     String picUrl;
 32     static File file;
 33          
 46     public String echart(){
 47         System.out.println("OK");
 48         this.list = new LinkedList<User>();
 49         this.list.add(new User("111","我是汉字"));
 50         this.list.add(new User("222","bbb"));
 51         this.list.add(new User("333","ccc"));
 52         
 53         reportParameters = new HashMap<String,String>();
 54         reportParameters.put("TIME", "2015");
 55         if(picUrl != null && !picUrl.equals("")){
 56             System.out.println("生成的图片绝对路径为:" + picUrl);
 57             reportParameters.put("picUrl", picUrl);
 58         }
 59         return "echart";
 60     }
 61     
 62     public void export() throws IOException{
 63         System.out.println("---------------------" + imgsURl);
 64         BASE64Decoder decoder = new BASE64Decoder();
 65         String[] url = imgsURl.split(",");
 66         String u = url[1];
 67         //Base64解码
 68         try
 69         {
 70             byte[] buffer = new BASE64Decoder().decodeBuffer(u);
 71             //生成图片
 72             String picName = new SimpleDateFormat("yyyyMMDD-HHmmssS").format(new Date());
 73             file = new File("e:/" + picName + ".png");
 74             OutputStream out = new FileOutputStream(file);    
 75             out.write(buffer);
 76             out.flush();
 77             out.close();
 78             System.out.println("生成图片成功,路径为:" + file.getAbsolutePath());
 79             outputWrite("success:" + file.getAbsolutePath());
 80         }
 81         catch (IOException e)
 82         {
 83             e.printStackTrace();
 84             outputWrite(e.getMessage());
 85         }
 86     }
 96     
 97     /***
 98      * 输出方法
 99      * @param outString 需要转换成json的串
100      * @throws IOException
101      */
102     public void outputWrite(Object outString) throws IOException {
103         PrintWriter out = null;
104         try {
105             HttpServletResponse response = ServletActionContext.getResponse();
106             response.setContentType("text/html; charset=UTF-8");
107             out = response.getWriter();
108             out.print(outString);
109             out.flush();
110         } finally {
111             if (out != null) {
112                 out.close();
113             }
114         }
115     }
116     
117     public Map<Object, Object> getExportParameters() {
118         return exportParameters;
119     }
120     public Map<String, String> getReportParameters() {
121         return reportParameters;
122     }
123     public void setReportParameters(Map<String, String> reportParameters) {
124         this.reportParameters = reportParameters;
125     }
126     public List<User> getList() {
127         return this.list;
128     }
129     public void setList(List<User> list) {
130         this.list = list;
131     }
132     public String getImgsURl()
133     {
134         return imgsURl;
135     }
136     public void setImgsURl(String imgsURl)
137     {
138         this.imgsURl = imgsURl;
139     }
140     public String getVaa()
141     {
142         return vaa;
143     }
144     public void setVaa(String vaa)
145     {
146         this.vaa = vaa;
147     }
148  
150     public String getPicUrl()
151     {
152         return picUrl;
153     }
154  
156     public void setPicUrl(String picUrl)
157     {
158         this.picUrl = picUrl;
159     }
160          
162 }

action里面就是获取到页面传入的参数,然后通过解析和解码,生成一张具体的图片~后续就是jasperReport获取到这个图片,然后显示excel中~

JasperAction#export()方法返回的值就包括了生成图片的路径,在js中,通过这句

var url="JasperAction_echart.action?picUrl=" + vaa.substring(8);
                    location.href=url;

就是一个下载的请求,该请求的路径就是JasperAction的echart()方法,后续就是JasperReport在struts2中的的导出方式了~

查看struts.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN" "http://struts.apache.org/dtds/struts-2.1.dtd">
<struts>
    <constant name="struts.devMode" value="true" />
    
    <package name="struts2" namespace="/" extends="struts-default,jasperreports-default">
    
        <action name="JasperAction_*" class="com.yzj.action.JasperAction" method="{1}">
            
            <result name="echart" type="jasper">
                <param name="location">/report/echart.jasper</param>
                <param name="dataSource">list</param>
                <param name="reportParameters">reportParameters</param>
                <param name="exportParameters">exportParameters</param>
                <param name="format">PDF</param>
            </result>
        </action>
        
    </package>
</struts>

JasperAction中使用的工具类和实体类:

package com.yzj.action;

public class User {
    
    private String username;
    private String password;
    
    public User(){}
    
    public User(String username,String password){
        this.username = username;
        this.password = password;
    }

    public String getUsername() {
        return username;
    }

    public String getPassword() {
        return password;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public void setPassword(String password) {
        this.password = password;
    }

}
 1 package com.yzj.action;
 2 
 3 import java.util.HashMap;
 4 import java.util.Map;
 5 
 6 import net.sf.jasperreports.engine.JRExporterParameter;
 7 import net.sf.jasperreports.engine.export.JExcelApiExporterParameter;
 8 import net.sf.jasperreports.engine.export.JRCsvExporterParameter;
 9 import net.sf.jasperreports.engine.export.JRXlsExporterParameter;
10 
11 public class JasperUtils {
12     
13     private final static Map map = new HashMap();
14     
15     static {
16         map.put(JRXlsExporterParameter.IS_ONE_PAGE_PER_SHEET, Boolean.TRUE);
17         map.put(JRXlsExporterParameter.IS_FONT_SIZE_FIX_ENABLED, Boolean.TRUE);
18         
19         map.put(JRXlsExporterParameter.PROPERTY_IGNORE_CELL_BORDER, Boolean.TRUE);
20         //对于导出excel来说下面三个很重要
21         map.put(JRXlsExporterParameter.IS_WHITE_PAGE_BACKGROUND, Boolean.FALSE);
22         map.put(JRXlsExporterParameter.IS_REMOVE_EMPTY_SPACE_BETWEEN_ROWS, Boolean.TRUE);
23         map.put(JRXlsExporterParameter.IS_REMOVE_EMPTY_SPACE_BETWEEN_COLUMNS, Boolean.TRUE);
24         
25         map.put(JExcelApiExporterParameter.IS_COLLAPSE_ROW_SPAN, Boolean.TRUE);
26         map.put(JRCsvExporterParameter.FIELD_DELIMITER, "");
27         map.put(JRExporterParameter.CHARACTER_ENCODING, "UTF-8");
28     }
29     
30     public static Map getMap(){
31         return map;
32     }
33 
34 }

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
    http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
    <filter>
        <filter-name>struts2</filter-name>
        <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>struts2</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
</web-app>

struts.xml中使用的echart.jasper,如下:

这里是echart.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="sss" language="groovy" pageWidth="842" pageHeight="595" orientation="Landscape" columnWidth="802" leftMargin="20" rightMargin="20" topMargin="20" bottomMargin="20">
    <property name="ireport.zoom" value="1.4641000000000006"/>
    <property name="ireport.x" value="0"/>
    <property name="ireport.y" value="0"/>
    <parameter name="TIME" class="java.lang.String"/>
    <field name="username" class="java.lang.String"/>
    <field name="password" class="java.lang.String"/>
    <field name="picUrl" class="java.lang.String"/>
    <background>
        <band splitType="Stretch"/>
    </background>
    <title>
        <band height="31" splitType="Stretch">
            <staticText>
                <reportElement x="107" y="0" width="295" height="31"/>
                <textElement textAlignment="Center">
                    <font size="14"/>
                </textElement>
                <text><![CDATA[Test Struts2 and JaspeRreports]]></text>
            </staticText>
        </band>
    </title>
    <pageHeader>
        <band height="26">
            <staticText>
                <reportElement x="243" y="0" width="159" height="25"/>
                <textElement>
                    <font size="12"/>
                </textElement>
                <text><![CDATA[password]]></text>
            </staticText>
            <staticText>
                <reportElement x="107" y="0" width="136" height="25"/>
                <textElement>
                    <font size="12"/>
                </textElement>
                <text><![CDATA[username]]></text>
            </staticText>
        </band>
    </pageHeader>
    <detail>
        <band height="186">
            <textField>
                <reportElement x="107" y="0" width="136" height="25"/>
                <textElement>
                    <font size="12"/>
                </textElement>
                <textFieldExpression><![CDATA[$F{username}]]></textFieldExpression>
            </textField>
            <image scaleImage="RealSize">
                <reportElement stretchType="RelativeToTallestObject" x="107" y="25" width="295" height="108"/>
                <imageExpression><![CDATA[$F{picUrl}]]></imageExpression>
            </image>
            <textField>
                <reportElement x="243" y="0" width="159" height="25"/>
                <textElement>
                    <font size="12"/>
                </textElement>
                <textFieldExpression><![CDATA[$F{password}]]></textFieldExpression>
            </textField>
        </band>
    </detail>
    <lastPageFooter>
        <band height="50">
            <textField>
                <reportElement x="243" y="0" width="159" height="20"/>
                <textElement/>
                <textFieldExpression><![CDATA[$P{TIME}]]></textFieldExpression>
            </textField>
        </band>
    </lastPageFooter>
</jasperReport>

 

将此内容复制下来存入文件中,文件的格式是jrxml

然后将此jrxml文件编译成jasper格式文件,两种方式,一种是代码的方式,可以百度jasperReport的教程,目前还不清楚怎么将编译后的文件持久化到硬盘

第二种就比较简单了,下载并安装ireport软件(注意ireport软件的版本号要和jasperReport的版本号一致,我都是使用4.5.1版本的),通过该软件打开.jrxml文件,然后点击

技术分享

即可编译完成

至此,项目中使用到的所有东西都准备完毕,剩余的就是jar包了~

提供工程下载如下:

 

如有什么问题,请留言

 

EChart整合JasperReport在struts2环境中导出

标签:

原文地址:http://www.cnblogs.com/seguzhizi/p/5445745.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!