Echarts折线图动态获取数据实例(附java后台代码)

前一段时间项目中要做数据统计,最后采用百度的echarts来做。之前写了一篇柱状图的用法,今天把折线图的写法分享一下。当时也是跳了很多坑参考了不少大神的文章,不过许多只是把jsp页面的js代码贴了出来没有java后台的,而我的项目需求是要能动态获取后台写法只能自己慢慢琢磨,虽然过程有点波折好在是按时完成需求,为了以后使用echarts动态获取数据的同学少跳坑我把代码分享出来,以供参考。

先前根据demo先做了一个静态数据的柱状图展示,静态图表展示是纯js代码,只要把后台el表达式${param}展示出来。折线图需求是要根据输入的查询时间,动态到数据库中查询数据,然后再展示到页面上。这就需要在后台增加两个java工具类来动态从后台获取横纵坐标的值,在controller中获取数据,jsp页面通过Ajax来传递数据,并把数据用echarts展示。

———————————————分割线————————————————————

先展示一下页面效果:用户选择查询的时间,根据时间默认查询出收入的数据,把查询到的数据展示给用户,用户可以点击按钮切换数据源
这里写图片描述

这里写图片描述

这里写图片描述

这里写图片描述

图表上的这些功能是由如下js代码控制的

这里写图片描述

jsp页面前台代码

echarts展示,Ajax获取数据

这里是两个按钮,切换收入、支出的数据显示

<div class="btn-group" data-toggle="buttons" style="margin-left: 70%">
        <label class="btn btn-success"> <input type="radio"
            name="options" id="option1" value="1" checked="checked" onclick="getInfo()">收入
        </label> <label class="btn btn-success"> <input type="radio"
            name="options" id="option2" value="2" onclick="getInfo()">支出
        </label>
    </div>

下面是echarts折线图的代码


<!-- 为ECharts准备一个具备大小(宽高)的Dom -->
    <div id="line" style="width: 95%; height: 400px;"></div>
    <script type="text/javascript">
        // 基于准备好的dom,初始化echarts实例
        var myChart = echarts.init(document.getElementById('line'));
        // 指定图表的配置项和数据
        var option = {
            title : {
                text : '收支明细折线图',
                subtext : 'demo'
            },
            tooltip : {
                show : true,
                trigger : 'axis'
            },
            legend : {
                data : [ "金额" ]
            //图例
            },
            dataZoom : [ {
                type : 'inside', //支持鼠标滚动缩放
                start : 0, //默认数据初始缩放范围为10%到90%
                end : 100
            } ],
            toolbox : {
                show : true,
                feature : {
                    mark : {
                        show : true
                    },
                    dataView : {
                        show : true,
                        readOnly : false
                    },
                    magicType : {
                        show : true,
                        type : [ 'bar', 'line' ]
                    },
                    restore : {
                        show : true
                    },
                    saveAsImage : {
                        show : true
                    }
                }
            },
            calculable : true,
            xAxis : [ {
                type : 'category',
                boundaryGap : false,
                data : []
            } ],
            yAxis : [ {
                name : '金额                       ', //Y轴提示
                type : 'value',
                //min: 0,
                //max: 30,
                // interval: 1,   //Y轴数据跨度              
                axisLabel : {
                    formatter : '{value} 元' //Y轴单位
                }
            } ],
            series : [ {
                "name" : "金额",
                "type" : "line",
                "data" : [],
                "smooth" : true, //主题--线条平滑
                "barWidth" : "70", //柱子宽度
                "symbol" : 'emptycircle', //设置折线图中表示每个坐标点的符号;emptycircle:空心圆;emptyrect:空心矩形;circle:实心圆;emptydiamond:菱形   
                "markPoint" : {
                    data : [ {
                        type : 'max',
                        name : '最大值'
                    }, {
                        type : 'min',
                        name : '最小值'
                    } ]
                },
                "markLine" : {
                    data : [ {
                        type : 'average',
                        name : '平均值'
                    } ]
                },
                //设置柱状图和节点的颜色
                itemStyle : {
                    normal : {
                        color : '#228B22',
                        //设置折线的颜色
                        lineStyle : {
                            color : '#228B22'
                        },
                        //以下为柱状图顶部是否显示,显示位置和显示格式的设置了
                        label : {
                            show : true,
                            textStyle : {
                                color : '#00CD66'
                            },
                            position : 'botton',
                            formatter : '\n{b}\n{c}(元)'
                        }
                    }
                }
            } //第一条折线
            ]
        };
        // 使用刚指定的配置项和数据显示图表。        
        myChart.setOption(option);
        //myChart.showLoading();
        var come = 1;
        getData(come);
        function getInfo() {
            var income = $("input[id='option1']:checked").val();
            var outcome = $("input[id='option2']:checked").val();
            if (income != null && outcome == null) {
                come = income;
            }
            if (income == null && outcome != null) {
                come = outcome;
            }
            if (income != null && outcome != null) {
                alert("只能选一种查看!");
            }
            getData(come);
        }
        function getData(come) {
            var b ="${orderCount.beginCreateDate}";
            var e ="${orderCount.endCreateDate}";
            var begin = new Date(b).toString();
            var end = new Date(e).toString();
            var option = myChart.getOption();           
            $.ajax({
                type : "post",
                async : false, //同步执行  
                url : "${ctx}/order/orderCount/Echarts",
                data : {
                    isIncome : come,
                    id : "${orderCount.accountid}",
                    type : "${orderCount.accountType}",
                    beginTime:begin,
                    endTime:end
                },
                dataType : "json", //返回数据形式为json  
                success : function(result) {
                    if (result) {
                        option.legend.data = result.legend;
                        option.xAxis[0].data = result.category;
                        option.series[0].data = result.series[0].data;
                        myChart.hideLoading();
                        myChart.setOption(option);
                        myChart.hideLoading();
                    }
                },
                error : function(errorMsg) {
                    alert("图表请求数据失败!");
                    //myChart.hideLoading();
                    myChart.showLoading();
                }
            });
        }
    </script>   

后台java代码,先配置两个工具类

1.Echarts.java

import java.util.ArrayList;
import java.util.List;

public class Echarts {
    public List<String> legend = new ArrayList<String>();//数据分组  
    public List<String> category = new ArrayList<String>();//横坐标  
    public List<Series> series = new ArrayList<Series>();//纵坐标  


    public Echarts(List<String> legendList, List<String> categoryList, List<Series> seriesList) {  
        super();  
        this.legend = legendList;  
        this.category = categoryList;  
        this.series = seriesList;  
    }  

}

2.Series.java



import java.math.BigDecimal;
import java.util.List;

public class Series {
    public String name;  

    public String type;  

    public List<BigDecimal> data;  
    public Series( String name, String type, List<BigDecimal> data) {  
        super();  
        this.name = name;  
        this.type = type;  
        this.data = data;  
    }  


}

贴出后台controller中代码

/**
     * echarts图表--查看收支金额
     * 2017.3.3
     * zz
     * **/
    @SuppressWarnings("deprecation")
    @RequiresPermissions("user")    
    @ResponseBody  
    @RequestMapping(value="Echarts")  
    public Echarts lineData(String id,String type,String isIncome,String beginTime,String endTime) {        
        OrderCountBo orderCount = new OrderCountBo();
        orderCount.setAccountid(id);
        orderCount.setAccountType(type);
        orderCount.setIsIncome(isIncome);                  //“1”是收入,“2”是支出
        orderCount.setBeginCreateDate(new Date(beginTime));
        orderCount.setEndCreateDate(new Date(endTime));
        //为时间设置,则自动赋值
        if(null==orderCount.getBeginCreateDate()||null==orderCount.getEndCreateDate()){
            orderCount.setEndCreateDate(new Date());
            Calendar calendar = Calendar.getInstance();    //得到日历
            calendar.setTime(new Date());                 //把当前时间赋给日历
            calendar.add(Calendar.DAY_OF_MONTH, -1);      //设置为前一天
            Date date = calendar.getTime();               //得到前一天的时间
            orderCount.setBeginCreateDate(date);            
        } 
        List<OrderCountBo> getList = orderCountService.getList(orderCount);    //查询获取数据
        List<String> category = new ArrayList<String>();
        List<BigDecimal>  index = new ArrayList<BigDecimal>();
        String getDate = null;
        BigDecimal getPrice = null;
        for(int i=0;i<getList.size();i++){                                     //循环获取数据
            OrderCountBo getOrderCount = getList.get(i); 
            getDate = DateUtils.formatDateTime(getOrderCount.getCreateLogDate());           
            getPrice = getOrderCount.getPrice();
            category.add(getDate);
            index.add(getPrice);
        }           
        List<String> legend = new ArrayList<String>(Arrays.asList(new String[]{"金额"}));//数据分组
        List<Series> series = new ArrayList<Series>();
        series.add(new Series("金额", "line",index));
        Echarts data=new Echarts(legend, category, series);
        return data;  
    }

猜你喜欢

转载自blog.csdn.net/tonyfreak/article/details/72553061