Echarts 数据视图 生成Excel的方法

Stella981
• 阅读 899

一、生成Excel,两大方向:
1后台生成Excel 

 查询数据库,使用NOPI生成Excel。
2前台js生成Excel三种方式
1)jquery.table2excel.js

--采用,优势:兼容IE和Chrome。

2)handsontable 0.32.0

问题:不兼容IE。
3)手写js有兼容性问题。

问题:浏览器兼容型问题等。

考虑到这里只需要将Echarts的数据视图生成Excel,采用最简单有效的方式:jquery.table2excel.js。

二、方案

       1、 jquery.table2excel.js  和Echarts数据视图结合的取巧方案

第一步:应用js脚本,先jquery脚本后table2excel脚本。

<script src="https://my.oschina.net//u/4275516/blog/3918822/Scripts/jquery-1.10.2.js"></script>

<script src="https://my.oschina.net//u/4275516/blog/3918822/Scripts/table2excel/jquery.table2excel.js"></script>

第二步:重写dataView-contentToOption方法,注意不能设为只读。

toolbox: {
                        right: '20px',

                        feature: {
                            dataView: {
                                show: true,
                                title: '数据视图',
                                //readOnly: true, //设置只读,会隐藏刷新按钮。
                                lang: ['数据视图', '关闭', '导出Excel'],
                                contentToOption: function (opts) {
                                    $("#tableExcel_Day").table2excel({
                                        exclude: ".noExl", //过滤位置的 css 类名
                                        filename: productSelectName + '每日价格走势图' + ".xls", //文件名称
                                        name: "Excel Document Name.xls",
                                        exclude_img: true,
                                        exclude_links: true,
                                        exclude_inputs: true
                                    });
                                },
                                optionToContent: function (opt) {
                                   // console.log(opt);

                                    var axisData = opt.xAxis[0].data; //坐标数据
                                    var series = opt.series; //折线图数据
                                    var tdHeads = '<td  style="padding: 0 10px">时间</td>'; //表头第一列
                                    var tdBodys = ''; //表数据
                                    //组装表头
                                    var nameData = new Array('田头价格', '批发价格', '零售价格', '交易量');
                                    for (var i = 0; i < nameData.length; i++) {
                                        tdHeads += '<td style="padding: 0 10px">' + nameData[i] + '</td>';
                                    }
                                    var table = '<table id="tableExcel_Day" border="1" class="table-bordered table-striped" style="width:100%;text-align:center" ><tbody><tr>' + tdHeads + ' </tr>';
                                    //组装表数据
                                    for (var i = 0, l = axisData.length; i < l; i++) {
                                        for (var j = 0; j < series.length ; j++) {                           
                                            var temp = series[j].data[i];
                                            if (temp != null && temp != undefined) {                                      
                                                tdBodys += '<td>' + temp.toFixed(2) + '</td>';       
                                            } else {
                                                tdBodys += '<td></td>';
                                            }
                                        }
                                        table += '<tr><td style="padding: 0 10px">' + axisData[i] + '</td>' + tdBodys + '</tr>';
                                        tdBodys = '';
                                    }
                                    table += '</tbody></table>';                                   
                                   // console.log(table);
                                    return table;
                                   
                                }
                            },
                            dataZoom: { show: true, title: { zoom: '区域缩放', back: '区域缩放还原' } },
                            saveAsImage: { show: true }
                        }
                    },

 解释 1、通过id即tableExcel_Day来找到表格。

            2、exclude: “.noExl” : 有class = “noExl” 的行不被导出; 

第三步:效果图

Echarts 数据视图 生成Excel的方法

点击“导出Excel”

Echarts 数据视图 生成Excel的方法

     存在的问题:点击“生成Excel”按钮后,视图会跳转,因为这是原本是刷新按钮,目前还未解决。

三、jquery.table2excel.js 脚本:

/*
 *  jQuery table2excel - v1.1.1
 *  jQuery plugin to export an .xls file in browser from an HTML table
 *  https://github.com/rainabba/jquery-table2excel
 *
 *  Made by rainabba
 *  Under MIT License
 */
/*
 *  jQuery table2excel - v1.1.1
 *  jQuery plugin to export an .xls file in browser from an HTML table
 *  https://github.com/rainabba/jquery-table2excel
 *
 *  Made by rainabba
 *  Under MIT License
 */
//table2excel.js
;(function ( $, window, document, undefined ) {
    var pluginName = "table2excel",

    defaults = {
        exclude: ".noExl",
        name: "Table2Excel",
        filename: "table2excel",
        fileext: ".xls",
        exclude_img: true,
        exclude_links: true,
        exclude_inputs: true
    };

    // The actual plugin constructor
    function Plugin ( element, options ) {
            this.element = element;
            // jQuery has an extend method which merges the contents of two or
            // more objects, storing the result in the first object. The first object
            // is generally empty as we don't want to alter the default options for
            // future instances of the plugin
            //
            this.settings = $.extend( {}, defaults, options );
            this._defaults = defaults;
            this._name = pluginName;
            this.init();
    }

    Plugin.prototype = {
        init: function () {
            var e = this;

            var utf8Heading = "<meta http-equiv=\"content-type\" content=\"application/vnd.ms-excel; charset=UTF-8\">";
            e.template = {
                head: "<html xmlns:o=\"urn:schemas-microsoft-com:office:office\" xmlns:x=\"urn:schemas-microsoft-com:office:excel\" xmlns=\"http://www.w3.org/TR/REC-html40\">" + utf8Heading + "<head><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets>",
                sheet: {
                    head: "<x:ExcelWorksheet><x:Name>",
                    tail: "</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet>"
                },
                mid: "</x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--></head><body>",
                table: {
                    head: "<table>",
                    tail: "</table>"
                },
                foot: "</body></html>"
            };

            e.tableRows = [];

            // get contents of table except for exclude
            $(e.element).each( function(i,o) {
                var tempRows = "";
                $(o).find("tr").not(e.settings.exclude).each(function (i,p) {
                    
                    tempRows += "<tr>";
                    $(p).find("td,th").not(e.settings.exclude).each(function (i,q) { // p did not exist, I corrected
                        
                        var rc = {
                            rows: $(this).attr("rowspan"),
                            cols: $(this).attr("colspan"),
                            flag: $(q).find(e.settings.exclude)
                        };
                        
                        if( rc.flag.length > 0 ) {
                            tempRows += "<td> </td>"; // exclude it!!
                        } else {
                            if( rc.rows  & rc.cols ) {
                                tempRows += "<td>" + $(q).html() + "</td>";
                            } else {
                                tempRows += "<td";
                                if( rc.rows > 0) {
                                    tempRows += " rowspan=\'" + rc.rows + "\' ";
                                }
                                if( rc.cols > 0) {
                                    tempRows += " colspan=\'" + rc.cols + "\' ";
                                }
                                tempRows += "/>" + $(q).html() + "</td>";
                            }
                        }
                    });

                    tempRows += "</tr>";
                   // console.log(tempRows);
                    
                });
                // exclude img tags
                if(e.settings.exclude_img) {
                    tempRows = exclude_img(tempRows);
                }

                // exclude link tags
                if(e.settings.exclude_links) {
                    tempRows = exclude_links(tempRows);
                }

                // exclude input tags
                if(e.settings.exclude_inputs) {
                    tempRows = exclude_inputs(tempRows);
                }
                e.tableRows.push(tempRows);
            });

            e.tableToExcel(e.tableRows, e.settings.name, e.settings.sheetName);
        },

        tableToExcel: function (table, name, sheetName) {
            var e = this, fullTemplate="", i, link, a;

            e.format = function (s, c) {
                return s.replace(/{(\w+)}/g, function (m, p) {
                    return c[p];
                });
            };

            sheetName = typeof sheetName === "undefined" ? "Sheet" : sheetName;

            e.ctx = {
                worksheet: name || "Worksheet",
                table: table,
                sheetName: sheetName
            };

            fullTemplate= e.template.head;

            if ( $.isArray(table) ) {
                for (i in table) {
                      //fullTemplate += e.template.sheet.head + "{worksheet" + i + "}" + e.template.sheet.tail;
                      fullTemplate += e.template.sheet.head + sheetName + i + e.template.sheet.tail;
                }
            }

            fullTemplate += e.template.mid;

            if ( $.isArray(table) ) {
                for (i in table) {
                    fullTemplate += e.template.table.head + "{table" + i + "}" + e.template.table.tail;
                }
            }

            fullTemplate += e.template.foot;

            for (i in table) {
                e.ctx["table" + i] = table[i];
            }
            delete e.ctx.table;

            var isIE = /*@cc_on!@*/false || !!document.documentMode; // this works with IE10 and IE11 both :)            
            //if (typeof msie !== "undefined" && msie > 0 || !!navigator.userAgent.match(/Trident.*rv\:11\./))      // this works ONLY with IE 11!!!
            if (isIE) {
                if (typeof Blob !== "undefined") {
                    //use blobs if we can
                    fullTemplate = e.format(fullTemplate, e.ctx); // with this, works with IE
                    fullTemplate = [fullTemplate];
                    //convert to array
                    var blob1 = new Blob(fullTemplate, { type: "text/html" });
                    window.navigator.msSaveBlob(blob1, getFileName(e.settings) );
                } else {
                    //otherwise use the iframe and save
                    //requires a blank iframe on page called txtArea1
                    txtArea1.document.open("text/html", "replace");
                    txtArea1.document.write(e.format(fullTemplate, e.ctx));
                    txtArea1.document.close();
                    txtArea1.focus();
                    sa = txtArea1.document.execCommand("SaveAs", true, getFileName(e.settings) );
                }

            } else {
                var blob = new Blob([e.format(fullTemplate, e.ctx)], {type: "application/vnd.ms-excel"});
                window.URL = window.URL || window.webkitURL;
                link = window.URL.createObjectURL(blob);
                a = document.createElement("a");
                a.download = getFileName(e.settings);
                a.href = link;

                document.body.appendChild(a);

                a.click();

                document.body.removeChild(a);
            }

            return true;
        }
    };

    function getFileName(settings) {
        return ( settings.filename ? settings.filename : "table2excel" );
    }

    // Removes all img tags
    function exclude_img(string) {
        var _patt = /(\s+alt\s*=\s*"([^"]*)"|\s+alt\s*=\s*'([^']*)')/i;
        return string.replace(/<img[^>]*>/gi, function myFunction(x){
            var res = _patt.exec(x);
            if (res !== null && res.length >=2) {
                return res[2];
            } else {
                return "";
            }
        });
    }

    // Removes all link tags
    function exclude_links(string) {
        return string.replace(/<a[^>]*>|<\/a>/gi, "");
    }

    // Removes input params
    function exclude_inputs(string) {
        var _patt = /(\s+value\s*=\s*"([^"]*)"|\s+value\s*=\s*'([^']*)')/i;
        return string.replace(/<input[^>]*>|<\/input>/gi, function myFunction(x){
            var res = _patt.exec(x);
            if (res !== null && res.length >=2) {
                return res[2];
            } else {
                return "";
            }
        });
    }

    $.fn[ pluginName ] = function ( options ) {
        var e = this;
            e.each(function() {
                if ( !$.data( e, "plugin_" + pluginName ) ) {
                    $.data( e, "plugin_" + pluginName, new Plugin( this, options ) );
                }
            });

        // chain jQuery functions
        return e;
    };

})( jQuery, window, document );

有朋友说想看看源码,特加上源码,请适当参考:

前端:

Echarts 数据视图 生成Excel的方法 Echarts 数据视图 生成Excel的方法

   1 @{
   2     ViewBag.Title = "价格行情";
   3     Layout = "~/Views/Shared/_Layout.cshtml";
   4 }
   5 
   6 
   7 <div class="row">
   8     <div class="col-md-6">
   9         <table>
  10             <tr>
  11                 <td style="width:20px"></td>
  12                 <td><label id="lbDateStart" style="width:70px">开始日期:</label></td>
  13                 <td>
  14                     <input id="boxDateStart" class="easyui-datebox" />
  15                 </td>
  16                 <td style="width:20px"></td>
  17                 <td><label id="lbDateEnd" style="width:70px">结束日期:</label></td>
  18                 <td>
  19                     <input id="boxDateEnd" class="easyui-datebox"  />
  20                 </td>
  21             </tr>
  22         </table>
  23     </div>
  24     <div class="col-md-6">
  25         <table>
  26             <tr>
  27                 <td style="width:90px"></td>
  28                 <td><label id="lbselectRegion">地区:</label></td>
  29                 <td>
  30                     <select class="easyui-combobox" id="selectRegion" data-options="required:false,label: $('#lbselectRegion'),width:150,labelWidth:50"></select>
  31                 </td>
  32                 <td style="width:20px"></td>
  33                 <td><label id="lbselectVegetableType">品种选择:</label></td>
  34                 <td>
  35                     <select class="easyui-combobox" id="selectVegetableType" data-options="required:false,label: $('#lbselectVegetableType'),width:200,labelWidth:80"></select>
  36                 </td>
  37             </tr>
  38         </table>
  39     </div>
  40 </div>
  41 <div class="row">
  42     <div id="cc" style="width:100%;height:20px; "></div>
  43 </div>
  44 
  45 <div class="row">
  46     <div class="col-md-6">
  47         <div id="someTimePriceForm" style="width:100%;height:400px;">
  48             <header>
  49                 <div class="panel-title">
  50                     <span id="SelectID_someTimePriceForm"></span>每日价格表
  51                     <span style="float:right;padding-right:15px">单位:元/千克</span>
  52                 </div>
  53             </header>
  54         </div>
  55     </div>
  56     <div class="col-md-6">
  57         <div id="someTimePrice" style="width:100%;height:400px; "></div>
  58     </div>
  59 </div>
  60 
  61 <div class="row">
  62     <div style="width:100%;height:20px; "></div>
  63 </div>
  64 <div class="row">
  65 
  66     <div class="col-md-12">
  67         <table>
  68             <tr>
  69                 <td style="width:20px"></td>
  70                 <td><label id="lbyearStartSelect_Week">开始年:</label></td>
  71                 <td>
  72                     <select class="easyui-combobox" id="yearStartSelect_WeekCombox" data-options="required:false,label: $('#lbyearStartSelect_Week'),width:150,labelWidth:50"></select>
  73                 </td>
  74                 <td style="width:20px"></td>
  75                 <td><label id="lbweekStartSelect">开始周:</label></td>
  76                 <td>
  77                     <select class="easyui-combobox" id="weekStartSelectCombox" data-options="required:false,label: $('#lbweekStartSelect'),width:150,labelWidth:50"></select>
  78                 </td>
  79                 <td style="width:90px"></td>
  80                 <td><label id="lbyearEndSelect_Week">结束年:</label></td>
  81                 <td>
  82                     <select class="easyui-combobox" id="yearEndSelect_WeekCombox" data-options="required:false,label: $('#lbyearEndSelect_Week'),width:150,labelWidth:50"></select>
  83                 </td>
  84                 <td style="width:20px"></td>
  85                 <td><label id="lbweekEndSelect">结束周:</label></td>
  86                 <td>
  87                     <select class="easyui-combobox" id="weekEndSelectCombox" data-options="required:false,label: $('#lbweekEndSelect'),width:150,labelWidth:50"></select>
  88                 </td>
  89             </tr>
  90         </table>
  91     </div>
  92 </div>
  93 
  94 <div class="row">
  95     <div style="width:100%;height:20px; "></div>
  96 </div>
  97 
  98 <div class="row">
  99     <div class="col-md-6">
 100         <div id="weekPriceListGrid" style="width:100%;height:400px;">
 101             <header>
 102                 <div class="panel-title">
 103                     <span id="SelectID_weekPriceListGrid"></span>周均价格表
 104                     <span style="float:right;padding-right:15px">单位:元/千克</span>
 105                 </div>
 106             </header>
 107         </div>
 108     </div>
 109 
 110     <div class="row">
 111         <div class="col-md-6">
 112             <div id="weekPrice" style="width:100%;height:400px;"></div>
 113         </div>
 114     </div>
 115 </div>
 116 
 117 <div class="row">
 118     <div style="width:100%;height:20px; "></div>
 119 </div>
 120 <div class="row">
 121     <div class="col-md-6">
 122         <table>
 123             <tr>
 124                 <td style="width:20px"></td>
 125                 <td><label id="lbYearMonthStart" style="width:70px">起始年月:</label></td>
 126                 <td>
 127                     <input id="attYearMonthStart" editable="false" name="attYearMonthStart" class="easyui-datebox" style="width: 172px" />
 128                 </td>
 129                 <td style="width:20px"></td>
 130                 <td><label id="lbYearMonthEnd" style="width:70px">终止年月:</label></td>
 131                 <td>
 132                     <input id="attYearMonthEnd" editable="false" name="attYearMonthEnd" class="easyui-datebox" style="width: 172px" />
 133                 </td>
 134             </tr>
 135         </table>
 136     </div>
 137 </div>
 138 <div class="row" >
 139     <div style="width:100%;height:20px; "></div>
 140 </div>
 141 
 142 <div class="row">
 143     <div class="col-md-6">
 144         <div id="monthlyPriceListGrid" style="width:100%;height:400px;">
 145             <header>
 146                 <div class="panel-title">
 147                     <span id="SelectID_monthlyPriceListGrid"></span>月均价格表
 148                     <span style="float:right;padding-right:15px">单位:元/千克</span>
 149                 </div>
 150             </header>
 151         </div>
 152     </div>
 153 
 154     <div class="col-md-6">
 155         <div id="monthPrice" style="width:100%;height:400px;">
 156         </div>
 157     </div>
 158  </div>
 159 
 160 <div class="row">
 161     <div style="width:100%;height:20px; "></div>
 162 </div>
 163 <div class="row">
 164     <div class="col-md-6">
 165         <table>
 166             <tr>
 167                 <td style="width:20px"></td>
 168                 <td><label id="lbselectDate">日期:</label></td>
 169                 <td>
 170                     <input  class="easyui-datebox" id="selectDate" data-options="required:false,label: $('#lbselectDate'),width:220,labelWidth:50" />
 171                 </td>
 172                 </tr>
 173             </table>
 174         </div>
 175     </div>
 176 <div class="row">
 177     <div style="width:100%;height:20px; "></div>
 178 </div>
 179 
 180     <div class="row">
 181         <div class="col-md-6">
 182             <div id="gridJghq" style="width:100%;height:400px;">
 183                 <header>
 184                     <div class="panel-title">
 185                         <span id="SelectID_gridJghq"></span>感兴趣品种价格表
 186                         <span style="float:right;padding-right:15px">单位:元/千克</span>
 187                     </div>
 188                 </header>
 189             </div>
 190         </div>
 191         <div class="col-md-6">
 192             <div id="regionProductsPrice" style="width:100%;height:400px;"></div>
 193         </div>
 194     </div>
 195 
 196     <div class="row">
 197         <div  style="width:100%;height:20px; "></div>
 198     </div>
 199     <div class="row">
 200         
 201         <div class="col-md-6">
 202             <div id="identicalProductDifferentRegions" style="width:100%;height:400px;">
 203                 <header>
 204                     <div class="panel-title">
 205                        感兴趣地区<span id="SelectID_DifferentRegions"></span>价格表
 206                         <span style="float:right;padding-right:15px">单位:元/千克</span>
 207                     </div>
 208                 </header>
 209                 
 210             </div>
 211         </div>
 212         <div class="col-md-6">
 213             <div id="productRegionsPrice" style="width:100%;height:400px;"></div>
 214         </div>
 215 
 216     </div>
 217 <div class="row">
 218     <div style="width:100%;height:20px; "></div>
 219 </div>
 220 
 221     <script type="text/javascript">
 222 
 223         var curr_time = new Date();
 224         var y = curr_time.getFullYear();
 225         var m = curr_time.getMonth();
 226         var d = curr_time.getDate();
 227         //近12个月
 228         var lastYear = new Date(y, m - 12, d);
 229         //近一月
 230         var lastMonth = new Date(y, m, d - 30);
 231         //近一天
 232         var lastDay = new Date(y, m, d - 1);
 233         //开始日期
 234         var startDay = myformatterDate(lastMonth);
 235         //结束日期
 236         var endDay = myformatterDate(curr_time);
 237         //开始年
 238         var yearStartSelect = lastYear.getFullYear();
 239         //开始月
 240         var monthStartSelect = lastYear.getMonth() + 1;
 241         //结束年
 242         var yearEndSelect = y;
 243         //结束月
 244         var monthEndSelect = m + 1;
 245         // 日期
 246         var selectDate = myformatterDate(lastDay);
 247         //品种
 248         var productSelect = null;
 249         //地区
 250         var locationSelect = null;
 251         //品种名称
 252         var productSelectName = null;
 253         //地区名称
 254         var locationSelectName = null;
 255         //品种下拉框
 256         var selectVegetableType = $("#selectVegetableType");
 257         //城市下拉框
 258         var selectRegion = $("#selectRegion");
 259 
 260         //品种选择
 261         var setProductValue = null;
 262 
 263         function loadJghq() {
 264 
 265             SomeTimePriceLineAJAXData(locationSelect, productSelect, startDay, endDay);
 266             $("#someTimePriceForm").datagrid("load", {
 267                 "regions": locationSelect,
 268                 "products": productSelect,
 269                 "start": startDay,
 270                 "end": endDay,
 271 
 272             });
 273         }
 274 
 275 
 276         //开始年_周下拉列表
 277         var yearStartSelect_WeekCombox = $("#yearStartSelect_WeekCombox");
 278         //开始周下拉列表
 279         var weekStartSelectCombox = $("#weekStartSelectCombox");
 280         //结束年_周下拉列表
 281         var yearEndSelect_WeekCombox = $("#yearEndSelect_WeekCombox");
 282         //结束周下拉列表
 283         var weekEndSelectCombox = $("#weekEndSelectCombox");
 284 
 285         //当前时间
 286         var date1 = new Date();
 287         var date2 = new Date();
 288         //设置为1月
 289         date2.setMonth(0);
 290         //设置为1日
 291         date2.setDate(1);
 292         var time = date1 - date2;
 293         //今天是今年第几天
 294         var day = Math.ceil(time / (24 * 60 * 60 * 1000));
 295         //今天是今年第几周
 296         var week = Math.ceil(day / 7);
 297         //下拉列表最大年份
 298         var yearFuture = date1.getFullYear();
 299         //下拉列表最小年份
 300         var yearPast = date1.getFullYear() - 9;
 301 
 302         //开始年_周
 303         var yearStartSelect_Week = date1.getFullYear() - 1;
 304         //开始周
 305         var weekStartSelect =  week;
 306         //结束年_周
 307         var yearEndSelect_Week = date1.getFullYear();
 308         //结束周
 309         var weekEndSelect = week;
 310 
 311 
 312         $(function () {
 313 
 314 
 315             //开始年、结束年下拉列表数据
 316             for (var j = yearPast; j <= yearFuture; j++) {
 317                 yearStartSelect_WeekCombox.append($("<option>").text(j).attr("value", j));
 318                 yearEndSelect_WeekCombox.append($("<option>").text(j).attr("value", j));
 319             }
 320             //开始周、结束周列表数据
 321             for (var i = 1; i <= 53; i++) {
 322                 weekStartSelectCombox.append($("<option>").text(i).attr("value", i));
 323                 weekEndSelectCombox.append($("<option>").text(i).attr("value", i));
 324             }
 325             //开始周默认选中项
 326             if (weekStartSelect != null) {
 327                 setTimeout('$("#weekStartSelectCombox").combobox("setValue", ' + weekStartSelect + ')', 100);
 328             }
 329             //结束周默认选中项
 330             if (weekEndSelect != null) {
 331                 setTimeout('$("#weekEndSelectCombox").combobox("setValue", ' + weekEndSelect + ')', 100);
 332             }
 333             //开始年默认选中项
 334             if (yearStartSelect_Week != null) {
 335                 setTimeout('$("#yearStartSelect_WeekCombox").combobox("setValue", ' + yearStartSelect_Week + ')', 100);
 336             }
 337             //结束年默认选中项
 338             if (yearEndSelect_Week != null) {
 339                 setTimeout('$("#yearEndSelect_WeekCombox").combobox("setValue", ' + yearEndSelect_Week + ')', 100);
 340             }
 341 
 342             //开始周初始化
 343             weekStartSelectCombox.combobox({
 344                 editable: false,
 345                 events: {
 346                     blur: function (s) {
 347                     }
 348                 },
 349                 onSelect: function (s) {
 350                     weekStartSelect = s.value;
 351                     WeekPriceCompareLineAJAXDataLoad(locationSelect, productSelect, yearStartSelect_Week, weekStartSelect, yearEndSelect_Week, weekEndSelect)
 352                 }
 353             });
 354             //结束周初始化
 355             weekEndSelectCombox.combobox({
 356                 editable: false,
 357                 events: {
 358                     blur: function (s) {
 359                     }
 360                 },
 361                 onSelect: function (s) {
 362                     weekEndSelect = s.value;
 363                     WeekPriceCompareLineAJAXDataLoad(locationSelect, productSelect, yearStartSelect_Week, weekStartSelect, yearEndSelect_Week, weekEndSelect)
 364                 }
 365             });
 366 
 367             //开始年初始化
 368             yearStartSelect_WeekCombox.combobox({
 369                 editable: false,
 370                 events: {
 371                     blur: function (s) {
 372                     }
 373                 },
 374                 onSelect: function (s) {
 375                     yearStartSelect_Week = s.value;
 376                     WeekPriceCompareLineAJAXDataLoad(locationSelect, productSelect, yearStartSelect_Week, weekStartSelect, yearEndSelect_Week, weekEndSelect)
 377 
 378                 }
 379             });
 380             //结束年初始化
 381             yearEndSelect_WeekCombox.combobox({
 382                 editable: false,
 383                 events: {
 384                     blur: function (s) {
 385                     }
 386                 },
 387                 onSelect: function (s) {
 388                     yearEndSelect_Week = s.value;
 389 
 390                     WeekPriceCompareLineAJAXDataLoad(locationSelect, productSelect, yearStartSelect_Week, weekStartSelect, yearEndSelect_Week, weekEndSelect)
 391                 }
 392             });
 393 
 394             // 周比较条件判断
 395             function WeekPriceCompareLineAJAXDataLoad(locationSelect, productSelect, yearStartSelect_Week, weekStartSelect, yearEndSelect_Week, weekEndSelect) {
 396                 if (locationSelect && productSelect && yearStartSelect_Week && weekStartSelect && yearEndSelect_Week && weekEndSelect) {
 397 
 398        
 399                         //周均价格行情表
 400                         $("#weekPriceListGrid").datagrid("load", {
 401                             "products": productSelect,
 402                             "regions": locationSelect,
 403                             "yearStart": yearStartSelect_Week,
 404                             "weekStart": weekStartSelect,
 405                             "yearEnd": yearEndSelect_Week,
 406                             "weekEnd": weekEndSelect
 407                         });
 408 
 409                         return WeekPriceCompareLineAJAXData(locationSelect, productSelect, yearStartSelect_Week, weekStartSelect, yearEndSelect_Week, weekEndSelect);
 410                    
 411                 }
 412             }
 413 
 414 
 415 
 416             for (var i in products) {
 417                 var canAdd = false;
 418                 if (!forecastPriceAll) {
 419                     for (var j in defaultFavorProductsValues) {
 420                         if (products[i].id == defaultFavorProductsValues[j]) {
 421                             canAdd = true;
 422                         }
 423                     }
 424                 }
 425                 else {
 426                     canAdd = true;
 427                 }
 428                 if (canAdd) {
 429 
 430                     var item = $("<option>").text(products[i].ncpmc).attr("value", products[i].id);
 431                     //if (item.length == 1) {
 432                     //    setProductValue = products[i].id;
 433                     //}
 434                     selectVegetableType.append(item);
 435 
 436 
 437                 }
 438             }
 439 
 440             //品种默认选中第一项
 441          
 442             setTimeout('$("#selectVegetableType").combobox("select",  ' + selectVegetableType[0][0].value+ ' )', 100);
 443          
 444 
 445             //地区
 446             var setRegionValue = null;
 447             for (var i in regionData) {
 448                 var canAdd = false;
 449                 for (var j in defaultFavorRegionValues) {
 450                     if (regionData[i].id == defaultFavorRegionValues[j]) {
 451                         canAdd = true;
 452                     }
 453                 }
 454 
 455                 if (regionData[i].id == defaultFavorRegionValues) {
 456                     canAdd = true;
 457                 }
 458                 if (canAdd) {
 459                     var item = $("<option>").text(regionData[i].cjdd).attr("value", regionData[i].id);
 460                     if (regionData[i].id == defaultRegion) {
 461                         setRegionValue = defaultRegion;
 462                     }
 463                     selectRegion.append(item);
 464                 }
 465             }
 466             //地区默认选中项
 467             if (setRegionValue != null) {
 468                 setTimeout('$("#selectRegion").combobox("setValue", ' + setRegionValue + ')', 100);
 469             }
 470 
 471 
 472 
 473             //地区combobox 设置
 474             selectRegion.combobox({
 475                 editable: false,
 476                 onSelect: function (s) {
 477                     locationSelect = s.value;
 478                     locationSelectName = s.text;
 479                     document.getElementById("SelectID_gridJghq").innerHTML = locationSelectName;
 480                     
 481 
 482                     //同一地区不同品种价格柱状图
 483                     RegionProductsPriceBarAJAXData(locationSelect, defaultFavorProductsValues, selectDate);
 484                     //价格行情曲线
 485                     SomeTimePriceLineAJAXData(locationSelect, productSelect, startDay, endDay);
 486                     WeekPriceCompareLineAJAXData(locationSelect, productSelect, yearStartSelect_Week, weekStartSelect, yearEndSelect_Week, weekEndSelect);
 487                     //月度价格行情曲线
 488                     MonthPriceLineAJAXData(locationSelect, productSelect, yearStartSelect, monthStartSelect, yearEndSelect, monthEndSelect);
 489                     //价格行情表
 490                     $("#someTimePriceForm").datagrid("load", {
 491                         "regions": locationSelect,
 492                         "products": productSelect,
 493                         "start": startDay,
 494                         "end": endDay,
 495                     });
 496                     //月均价格行情表
 497                     $("#monthlyPriceListGrid").datagrid("load", {
 498                         "products": productSelect,
 499                         "regions": locationSelect,
 500                         "yearStart": yearStartSelect,
 501                         "monthStart": monthStartSelect,
 502                         "yearEnd": yearEndSelect,
 503                         "monthEnd": monthEndSelect
 504                     });
 505 
 506 
 507                     //周均价格行情表
 508                     $("#weekPriceListGrid").datagrid("load", {
 509                         "products": productSelect,
 510                         "regions": locationSelect,
 511                         "yearStart": yearStartSelect_Week,
 512                         "weekStart": weekStartSelect,
 513                         "yearEnd": yearEndSelect_Week,
 514                         "weekEnd": weekEndSelect
 515                     });
 516                   
 517                     //同一地区不同品种价格柱状图
 518                     $("#gridJghq").datagrid("load", {
 519                         "products": productSelect,
 520                         "regions": locationSelect,
 521                         "date": selectDate
 522                     });
 523 
 524 
 525 
 526                 },
 527                 //onChange: function (s) {
 528                 //    if (s == "") {
 529                 //        $("#monthlyPriceListGrid").datagrid("load", {});
 530 
 531                 //    }
 532                 //}
 533             });
 534             //品种选择combobox 设置
 535             selectVegetableType.combobox({
 536                 editable: false,
 537                 events: {
 538                     blur: function (s) {
 539                         //selectVegetableType.combobox();
 540                     }
 541                 },
 542                 onSelect: function (s) {
 543                     productSelect = s.value;
 544                     productSelectName = s.text;
 545 
 546                     document.getElementById("SelectID_someTimePriceForm").innerHTML = productSelectName;
 547                     document.getElementById("SelectID_weekPriceListGrid").innerHTML = productSelectName;
 548                     document.getElementById("SelectID_monthlyPriceListGrid").innerHTML = productSelectName;
 549                     document.getElementById("SelectID_DifferentRegions").innerHTML = productSelectName;
 550                     //同一品种不同地区价格柱状图
 551                     ProductRegionsPriceBarAJAXData(defaultFavorRegionValues, productSelect, selectDate);
 552                     //价格行情曲线
 553                     SomeTimePriceLineAJAXData(locationSelect, productSelect, startDay, endDay);
 554                     WeekPriceCompareLineAJAXData(locationSelect, productSelect, yearStartSelect_Week, weekStartSelect, yearEndSelect_Week, weekEndSelect);
 555                     //价格行情表
 556                     $("#someTimePriceForm").datagrid("load", {
 557                         "regions": locationSelect,
 558                         "products": productSelect,
 559                         "start": startDay,
 560                         "end": endDay,
 561                     });
 562                     //月度价格行情曲线
 563                     MonthPriceLineAJAXData(locationSelect, productSelect, yearStartSelect, monthStartSelect, yearEndSelect, monthEndSelect);
 564                     //月度价格行情表
 565                     $("#monthlyPriceListGrid").datagrid("load", {
 566                         "products": productSelect,
 567                         "regions": locationSelect,
 568                         "yearStart": yearStartSelect,
 569                         "monthStart": monthStartSelect,
 570                         "yearEnd": yearEndSelect,
 571                         "monthEnd": monthEndSelect
 572                     });
 573                     //周均价格行情表
 574                     $("#weekPriceListGrid").datagrid("load", {
 575                         "products": productSelect,
 576                         "regions": locationSelect,
 577                         "yearStart": yearStartSelect_Week,
 578                         "weekStart": weekStartSelect,
 579                         "yearEnd": yearEndSelect_Week,
 580                         "weekEnd": weekEndSelect
 581                     });
 582                     //同一品种不同地区价格柱状图
 583                     $("#identicalProductDifferentRegions").datagrid("load", {
 584                         "products": productSelect,
 585                         // "regions": locationSelect,
 586                         "date": selectDate
 587                     });
 588                  
 589                 },
 590 
 591             });
 592 
 593             //开始时间
 594             $('#boxDateStart').datebox({
 595                 editable: false,
 596                 onSelect: function (startDate) {
 597                     
 598                     startDay = $("#boxDateStart").datebox("getValue");
 599 
 600                     var startDate = new Date(startDay);
 601                     var endDate = new Date(endDay);
 602                     if (startDate > endDate) {
 603                         endDay = startDay;
 604                         $("#boxDateEnd").datebox("setValue", endDay);
 605                     }
 606 
 607                     loadJghq();
 608                 },
 609                 
 610                 
 611             });
 612             //结束时间
 613             $('#boxDateEnd').datebox({
 614                 editable: false,
 615                 onSelect: function (endDate) {
 616                     endDay = $("#boxDateEnd").datebox("getValue");
 617 
 618                     var startDate = new Date(startDay);
 619                     var endDate = new Date(endDay);
 620                     if (startDate > endDate) {
 621                         startDay = endDay;
 622                         $("#boxDateStart").datebox("setValue", endDay);
 623                     }
 624 
 625                     loadJghq();
 626                 },
 627                 onChange:function (newValue,oldValue){
 628                     endDay = newValue;
 629                     loadJghq();
 630 
 631                 }
 632 
 633             });
 634 
 635             
 636 
 637             //日期选择对象
 638             var p = $('#attYearMonthStart').datebox('panel'),
 639             //日期选择对象中月份
 640             tds = false,
 641             //显示月份层的触发控件
 642             span = p.find('span.calendar-text');
 643             //开始年月
 644             $('#attYearMonthStart').datebox({
 645                 //显示日趋选择对象后再触发弹出月份层的事件,初始化时没有生成月份层
 646                 onShowPanel: function () {
 647                     //触发click事件弹出月份层
 648                     span.trigger('click');
 649                     if (!tds)
 650                         //延时触发获取月份对象,因为上面的事件触发和对象生成有时间间隔
 651                         setTimeout(function () {
 652                             tds = p.find('div.calendar-menu-month-inner td');
 653                             tds.click(function (e) {
 654                                 //禁止冒泡执行easyui给月份绑定的事件
 655                                 e.stopPropagation();
 656                                 //得到年份
 657                                 var year = /\d{4}/.exec(span.html())[0],
 658                                 //月份
 659                                 month = parseInt($(this).attr('abbr'), 10);
 660 
 661                                 //隐藏日期对象
 662                                 $('#attYearMonthStart').datebox('hidePanel')
 663                                   //设置日期的值
 664                                   .datebox('setValue', year + '-' + month);
 665 
 666                             });
 667                         }, 0);
 668                 },
 669                 //配置parser,返回选择的日期
 670                 parser: function (s) {
 671                     if (!s) return new Date();
 672                     var arr = s.split('-');
 673                     return new Date(parseInt(arr[0], 10), parseInt(arr[1], 10) - 1, 1);
 674                 },
 675                 //配置formatter,只返回年月
 676                 formatter: function (d) {
 677                     var currentMonth = (d.getMonth() + 1);
 678                     var currentMonthStr = currentMonth < 10 ? ('0' + currentMonth) : (currentMonth + '');
 679                     //  alert(d.getFullYear() + "-" + currentMonthStr);
 680                     return d.getFullYear() + '-' + currentMonthStr;
 681                 },
 682 
 683                 onChange: function (newValue, oldValue) {
 684                     yearStartSelect = parseInt(newValue.split('-')[0]);
 685                     monthStartSelect = parseInt(newValue.split('-')[1]);
 686                     //获取开始和结束时间
 687                     var start = yearStartSelect + '-' + monthStartSelect + '-' + 1;
 688                     var end = yearEndSelect + '-' + monthEndSelect + '-' + 1;
 689 
 690                     //日期比较方法
 691                     function CompareDate(d1, d2) {
 692                         return ((new Date(d1.replace(/-/g, "\/"))) <= (new Date(d2.replace(/-/g, "\/"))));
 693                     }
 694                     if (end != "null-null-1") {
 695                         //如果开始时间<=结束时间就执行以下代码
 696                         if (CompareDate(start, end)) {
 697                             //月度价格行情曲线
 698                             MonthPriceLineAJAXData(locationSelect, productSelect, yearStartSelect, monthStartSelect, yearEndSelect, monthEndSelect);
 699                             //月度价格行情表
 700                             $("#monthlyPriceListGrid").datagrid("load", {
 701                                 "products": productSelect,
 702                                 "regions": locationSelect,
 703                                 "yearStart": yearStartSelect,
 704                                 "monthStart": monthStartSelect,
 705                                 "yearEnd": yearEndSelect,
 706                                 "monthEnd": monthEndSelect
 707                             });
 708                         } else {
 709                             $('#attYearMonthEnd').datebox("setValue", newValue)
 710                         }
 711                     }
 712                 },
 713 
 714             });
 715 
 716 
 717 
 718 
 719             //日期选择对象
 720             var p_2 = $('#attYearMonthEnd').datebox('panel'),
 721             //日期选择对象中月份
 722             tds_2 = false,
 723             //显示月份层的触发控件
 724             span_2 = p_2.find('span.calendar-text');
 725 
 726             //结束年月
 727             $('#attYearMonthEnd').datebox({
 728 
 729                 //显示期选择对象后再触发弹出月份层的事件,初始化时没有生成月份层
 730                 onShowPanel: function () {
 731                     //触发click事件弹出月份层
 732                     span_2.trigger('click');
 733                     if (!tds_2){ 
 734                         //延时触发获取月份对象,因为上面的事件触发和对象生成有时间间隔
 735                     setTimeout(function () {
 736                             tds_2 = p_2.find('div.calendar-menu-month-inner td');
 737                             tds_2.click(function (e) {
 738                                 //禁止冒泡执行easyui给月份绑定的事件
 739                                 e.stopPropagation();
 740                                 //得到年份
 741                                 var year = /\d{4}/.exec(span_2.html())[0],
 742                                 //月份
 743                                 //之前是这样的month = parseInt($(this).attr('abbr'), 10) + 1;
 744                                 month = parseInt($(this).attr('abbr'), 10);
 745 
 746 
 747                                 //隐藏日期对象
 748                                 $('#attYearMonthEnd').datebox('hidePanel')
 749                                   //设置日期的值
 750                                 .datebox('setValue', year + '-' + month);
 751 
 752                             });
 753                      }, 0);
 754 
 755 
 756                     }
 757 
 758 
 759 
 760                 },
 761 
 762                 onChange: function (newValue, oldValue) {
 763 
 764                     yearEndSelect = parseInt(newValue.split('-')[0]);
 765                     monthEndSelect = parseInt(newValue.split('-')[1]);
 766                     //获取开始和结束时间
 767                     var start = yearStartSelect + '-' + monthStartSelect + '-' + 1;
 768                     var end = yearEndSelect + '-' + monthEndSelect + '-' + 1;
 769 
 770                     //日期比较方法
 771                     function CompareDate(d1, d2) {
 772                         return ((new Date(d1.replace(/-/g, "\/"))) <= (new Date(d2.replace(/-/g, "\/"))));
 773                     }
 774                                 
 775                     //如果开始时间<=结束时间就执行以下代码
 776                     if (CompareDate(start, end)) {
 777                         //月度价格行情曲线
 778                         MonthPriceLineAJAXData(locationSelect, productSelect, yearStartSelect, monthStartSelect, yearEndSelect, monthEndSelect);
 779                         //月度价格行情表
 780                         $("#monthlyPriceListGrid").datagrid("load", {
 781                             "products": productSelect,
 782                             "regions": locationSelect,
 783                             "yearStart": yearStartSelect,
 784                             "monthStart": monthStartSelect,
 785                             "yearEnd": yearEndSelect,
 786                             "monthEnd": monthEndSelect
 787                         });
 788                     } else {
 789                         $('#attYearMonthStart').datebox("setValue", newValue)
 790                     }
 791                     
 792 
 793 
 794                },
 795                 //配置parser,返回选择的日期
 796                 parser: function (s) {
 797                     if (!s) return new Date();
 798                     var arr = s.split('-');
 799                     return new Date(parseInt(arr[0], 10), parseInt(arr[1], 10) - 1, 1);
 800                 },
 801                 //配置formatter,只返回年月
 802                 formatter: function (d) {
 803                     var currentMonth = (d.getMonth() + 1);
 804                     var currentMonthStr = currentMonth < 10 ? ('0' + currentMonth) : (currentMonth + '');
 805                     // alert(d.getFullYear() + "-" + currentMonthStr);
 806 
 807                     return d.getFullYear() + '-' + currentMonthStr;
 808                 },
 809 
 810 
 811          
 812             });
 813 
 814             $("#selectDate").datebox({
 815                 editable: false,
 816                 onSelect: function (s) {
 817                     selectDate = $.fn.datebox.defaults.formatter(s);
 818 
 819                     TodayloadData();
 820 
 821                 },
 822                 onChange: function (newValue, oldValue) {
 823                     selectDate = newValue;
 824                     TodayloadData();
 825 
 826                 }
 827 
 828             });
 829 
 830             function TodayloadData() {
 831 
 832                 //同一地区不同品种价格柱状图
 833                 $("#gridJghq").datagrid("load", {
 834                     "products": productSelect,
 835                     "regions": locationSelect,
 836                     "date": selectDate
 837                 });
 838                 //同一品种不同地区价格柱状图
 839                 $("#identicalProductDifferentRegions").datagrid("load", {
 840                     "products": productSelect,
 841                     // "regions": locationSelect,
 842                     "date": selectDate
 843                 });
 844                 //同一地区不同品种价格柱状图
 845                 RegionProductsPriceBarAJAXData(locationSelect, defaultFavorProductsValues, selectDate);
 846                 //同一品种不同地区的价格柱状图
 847                 ProductRegionsPriceBarAJAXData(defaultFavorRegionValues, productSelect, selectDate);
 848 
 849             }
 850 
 851 
 852                     //价格行情表()
 853                     $("#someTimePriceForm").datagrid({
 854                         // title: "每日价格表",
 855                         
 856                         url: '@Url.Action("SomeTimePriceFormDataAjax")',
 857                         method: "get",
 858                         dataType: "json",
 859                         height: 400,
 860                         idField: "ID",
 861                         pageSize: 20,
 862                         singleSelect: true,
 863                         multiSort: true,
 864                         columns: [[
 865                             { field: 'cjrq', title: '日期', width: '15%', sortable: true, halign: 'center', align: 'center', formatter: formatDate },
 866                             { field: 'yjxzqname', title: '地区', width: '15%', halign: 'center', align: 'center' },
 867                             { field: 'ncpmc', title: '品种', width: '15%', sortable: true, halign: 'center', align: 'center' },
 868                             { field: 'ttjg', title: '田头价格', width: '13%', halign: 'center', align: 'center', formatter: formatFloat },
 869                             { field: 'pfjg', title: '批发价格', width: '13%', halign: 'center', align: 'center', formatter: formatFloat },
 870                             { field: 'lsjg', title: '零售价格', width: '13%', halign: 'center', align: 'center', formatter: formatFloat },
 871                             { field: 'jyl', title: '交易量(吨)', width: '16%', halign: 'center', align: 'center', formatter: formatFloat },
 872                         ]],
 873                         pagination: true,
 874                         remoteFilter: true,
 875                         rownumbers: true,
 876                         loader: function (param, success, error) {
 877                             //  param.regions = defaultFavorRegionValues.toString();
 878                             //  param.products = defaultFavorProductsValues.toString();
 879                             $.ajax({
 880                                 url: "@Url.Action("SomeTimePriceFormDataAjax")",
 881                                 data: param,
 882                             type: "get",
 883                             dataType: "json",
 884                             //contentType: "application/json",
 885                             success: function (data) {
 886                                 success(data);
 887                             }
 888                         });
 889                 }
 890                 });
 891 
 892             //周均价格行情表
 893             $("#weekPriceListGrid").datagrid({
 894                 // title: "周均价格表",
 895                 url: '@Url.Action("weekPriceList")',
 896                 method: "get",
 897                 dataType: "json",
 898                 height: 400,
 899                 idField: "ID",
 900                 pageSize: 20,
 901                 singleSelect: true,
 902                 multiSort: true,
 903                 columns: [[
 904                     { field: 'cjyear', title: '年', width: '10%', sortable: true, halign: 'center', align: 'center' },
 905                     { field: 'cjweek', title: '周', width: '8%', sortable: true, halign: 'center', align: 'center' },
 906                     { field: 'yjxzqname', title: '地区', width: '13%', halign: 'center', align: 'center' },
 907                     { field: 'ncpmc', title: '品种', width: '15%',  halign: 'center', align: 'center' },
 908                     { field: 'ttjg', title: '田头价格', width: '12%', halign: 'center', align: 'center', formatter: formatFloat },
 909                     { field: 'pfjg', title: '批发价格', width: '12%', halign: 'center', align: 'center', formatter: formatFloat },
 910                     { field: 'lsjg', title: '零售价格', width: '12%', halign: 'center', align: 'center', formatter: formatFloat },
 911                     { field: 'jyl', title: '交易量(吨)', width: '18%', halign: 'center', align: 'center', formatter: formatFloat },
 912                 ]],
 913 
 914                 pagination: true,
 915                 remoteFilter: true,
 916                 rownumbers: true,
 917                 loader: function (param, success, error) {
 918                     //  param.regions = defaultFavorRegionValues.toString();
 919                     //  param.products = defaultFavorProductsValues.toString();
 920                     //param.regions = locationSelect;
 921                     //param.products=productSelect;
 922                     $.ajax({
 923                         url: "@Url.Action("WeekPriceList")",
 924                         data: param,
 925                     type: "get",
 926                     dataType: "json",
 927                     //contentType: "application/json",
 928                     success: function (data) {
 929                         success(data);
 930                     }
 931                 });
 932         }
 933         });
 934 
 935 
 936                 //月均价格行情表
 937                 $("#monthlyPriceListGrid").datagrid({
 938                    // title: "月均价格表",
 939                     url: '@Url.Action("MonthlyPriceList")',
 940                     method: "get",
 941                     dataType: "json",
 942                     height: 400,
 943                     idField: "ID",
 944                     pageSize: 20,
 945                     singleSelect: true,
 946                     multiSort: true,
 947                     columns: [[
 948                         { field: 'cjyear', title: '年', width: '10%', sortable: true, halign: 'center', align: 'center' },
 949                         { field: 'cjmonth', title: '月', width: '8%', sortable: true, halign: 'center', align: 'center' },
 950                         { field: 'yjxzqname', title: '地区', width: '13%', halign: 'center', align: 'center' },
 951                         { field: 'ncpmc', title: '品种', width: '15%',  halign: 'center', align: 'center' },
 952                         { field: 'ttjg', title: '田头价格', width: '12%', halign: 'center', align: 'center', formatter: formatFloat },
 953                         { field: 'pfjg', title: '批发价格', width: '12%', halign: 'center', align: 'center', formatter: formatFloat },
 954                         { field: 'lsjg', title: '零售价格', width: '12%', halign: 'center', align: 'center', formatter: formatFloat },
 955                         { field: 'jyl', title: '交易量(吨)', width: '18%', halign: 'center', align: 'center', formatter: formatFloat },
 956                     ]],
 957 
 958                     pagination: true,
 959                     remoteFilter: true,
 960                     rownumbers: true,
 961                     loader: function (param, success, error) {
 962                         //  param.regions = defaultFavorRegionValues.toString();
 963                         //  param.products = defaultFavorProductsValues.toString();
 964                         //param.regions = locationSelect;
 965                         //param.products=productSelect;
 966                         $.ajax({
 967                             url: "@Url.Action("MonthlyPriceList")",
 968                             data: param,
 969                         type: "get",
 970                         dataType: "json",
 971                         //contentType: "application/json",
 972                         success: function (data) {
 973                             success(data);
 974                         }
 975                     });
 976                 }
 977                 });
 978 
 979 
 980                 //同一地区不同品种价格表
 981                 $("#gridJghq").datagrid({
 982                  //   title: "感兴趣品种价格表",
 983                     url: '@Url.Action("yjdatealljg")',
 984                     method: "get",
 985                     dataType: "json",
 986                     height: 400,
 987                     idField: "ID",
 988                     pageSize: 20,
 989                     singleSelect: true,
 990                     multiSort: true,
 991                     columns: [[
 992                         { field: 'cjrq', title: '日期', width: '15%', sortable: true, halign: 'center', align: 'center', formatter: formatDate },
 993                         { field: 'yjxzqname', title: '地区', width: '15%', halign: 'center', align: 'center' },
 994                         { field: 'ncpmc', title: '品种', width: '15%', sortable: true, halign: 'center', align: 'center' },
 995                         { field: 'ttjg', title: '田头价格', width: '13%', halign: 'center', align: 'center', formatter: formatFloat },
 996                         { field: 'pfjg', title: '批发价格', width: '13%', halign: 'center', align: 'center', formatter: formatFloat },
 997                         { field: 'lsjg', title: '零售价格', width: '13%', halign: 'center', align: 'center', formatter: formatFloat },
 998                         { field: 'jyl', title: '交易量(吨)', width: '16%', halign: 'center', align: 'center', formatter: formatFloat },
 999                     ]],
1000 
1001                     pagination: true,
1002                     remoteFilter: true,
1003                     rownumbers: true,
1004                     loader: function (param, success, error) {
1005                         //  param.regions = defaultFavorRegionValues.toString();
1006                         param.products = defaultFavorProductsValues.toString();
1007                         console.log(defaultFavorProductsValues);
1008                         console.log(param.products);
1009 
1010                         $.ajax({
1011                             url: "@Url.Action("yjdatealljg")",
1012                             data: param,
1013                         type: "get",
1014                         dataType: "json",
1015                         //contentType: "application/json",
1016                         success: function (data) {
1017                             success(data);
1018                         }
1019                     });
1020                 }
1021                 });
1022 
1023             //同一品种不同地区价格表
1024             $("#identicalProductDifferentRegions").datagrid({
1025               //  title: "感兴趣地区价格表",
1026                 url: '@Url.Action("IdenticalProductDifferentRegionsAjaxData")',
1027                 method: "get",
1028                 dataType: "json",
1029                 height: 400,
1030                 idField: "ID",
1031                 pageSize: 20,
1032                 singleSelect: true,
1033                 multiSort: true,
1034                 columns: [[
1035                     { field: 'cjrq', title: '日期', width: '15%', sortable: true, halign: 'center', align: 'center', formatter: formatDate },
1036                     { field: 'yjxzqname', title: '地区', width: '15%', halign: 'center', align: 'center' },
1037                     { field: 'ncpmc', title: '品种', width: '15%', sortable: true, halign: 'center', align: 'center' },
1038                     { field: 'ttjg', title: '田头价格', width: '13%', halign: 'center', align: 'center', formatter: formatFloat },
1039                     { field: 'pfjg', title: '批发价格', width: '13%', halign: 'center', align: 'center', formatter: formatFloat },
1040                     { field: 'lsjg', title: '零售价格', width: '13%', halign: 'center', align: 'center', formatter: formatFloat },
1041                     { field: 'jyl', title: '交易量(吨)', width: '16%', halign: 'center', align: 'center', formatter: formatFloat },
1042                 ]],
1043 
1044                 pagination: true,
1045                 remoteFilter: true,
1046                 rownumbers: true,
1047                 loader: function (param, success, error) {
1048                      param.regions = defaultFavorRegionValues.toString();
1049                     $.ajax({
1050                         url: "@Url.Action("IdenticalProductDifferentRegionsAjaxData")",
1051                         data: param,
1052                     type: "get",
1053                     dataType: "json",
1054                     //contentType: "application/json",
1055                     success: function (data) {
1056                         success(data);
1057                     }
1058                 });
1059         }
1060         });
1061 
1062   
1063 
1064             // 设置当月         
1065             $("#attYearMonthStart").datebox("setValue", myformatterDY(lastYear));
1066             $("#attYearMonthEnd").datebox("setValue", myformatterDY(curr_time));
1067             //设置日期
1068             $("#boxDateStart").datebox("setValue", myformatterDate(lastMonth));
1069             $("#boxDateEnd").datebox("setValue", myformatterDate(curr_time));
1070             //日期
1071             $("#selectDate").datebox("setValue", myformatterDate(lastDay));
1072 
1073         });
1074 
1075 
1076         // 格式化日期
1077         function myformatterDY(date) {
1078             //获取年份
1079             var y = date.getFullYear();
1080             //获取月份
1081             var m = date.getMonth() + 1;
1082             return y + '-' + m;
1083         }
1084 
1085         function myformatterDate(date) {
1086             var y = date.getFullYear();
1087             var m = date.getMonth() + 1;
1088             var d = date.getDate();
1089             return y + '-' + (m < 10 ? ('0' + m) : m) + '-' + (d < 10 ? ('0' + d) : d);
1090         }
1091 
1092 
1093         function formatFloat(val, row) {
1094             if (val == null) { return null; }
1095             return val.toFixed(2);
1096         }
1097 
1098         function formatDate(val, row) {
1099             //return new Date(val).Format("yyyy-MM-dd");
1100             return $.fn.datebox.defaults.formatter(new Date(val))
1101         }
1102 
1103 
1104 
1105 
1106 
1107         //价格行情曲线(第一排右侧) 选中品种一段日期的三个价格行情曲线
1108         var chart_someTimePrice_line = echarts.init(document.getElementById('someTimePrice'));
1109         option = {
1110             title: {
1111                 text: '价格走势图',
1112                 left: "center",
1113             },
1114             tooltip: {
1115                 trigger: 'axis'
1116             },
1117             legend: {
1118                 data: ['田头价格', '批发价格', '零售价格'],
1119                 top: '30px',
1120             },
1121             grid: {
1122                 left: '3%',
1123                 right: '4%',
1124                 bottom: '3%',
1125                 containLabel: true,
1126           
1127             },
1128 
1129             toolbox: {
1130                 right: '20px',
1131                 feature: {
1132                     dataZoom: { show: true, title: { zoom: '区域缩放', back: '区域缩放还原' } },
1133                     saveAsImage: { show: true }
1134                 }
1135             },
1136             xAxis: {
1137 
1138                 type: 'category',
1139                 boundaryGap: false,
1140                 data: [],
1141 
1142             },
1143             yAxis: {
1144 
1145 
1146                 type: 'value',
1147                 min: function (value) {
1148                     return Math.floor(value.min - 0.1);
1149                 }
1150 
1151             },
1152             series: [
1153                 {
1154                     name: '田头价格',
1155                     type: 'line',
1156                     data: [],
1157                 },
1158                 {
1159                     name: '批发价格',
1160                     type: 'line',
1161                     data: [],
1162                 },
1163 
1164                 {
1165                     name: '零售价格',
1166                     type: 'line',
1167                     data: [],
1168 
1169                 },
1170 
1171 
1172             ],
1173             tooltip: {
1174                 trigger: 'axis',
1175 
1176             }
1177         };
1178         function SomeTimePriceLineAJAXData(locationSelect, productSelect, startDay, endDay) {
1179             //异步加载数据
1180             var url = "@Url.Action("SomeTimePriceLineAJAXData")";
1181             if (locationSelect && productSelect && startDay && endDay) {
1182                 $.post(url, { yjxzqid: locationSelect, ncpid: productSelect, start: startDay, end: endDay }, function (result) {
1183 
1184 
1185                     chart_someTimePrice_line.setOption({
1186                         title: {
1187                             text: productSelectName+'每日价格走势图',
1188                             left: "center",
1189                         },
1190 
1191                         legend: {
1192                             data: ['田头价格', '批发价格', '零售价格', '交易量'],
1193                             top: '30px',
1194                         },
1195                         grid: {
1196                             left: '3%',
1197                             right: '4%',
1198                             bottom: '3%',
1199                             containLabel: true,
1200 
1201                         },
1202 
1203                         toolbox: {
1204                             right: '20px',
1205                             feature: {
1206                                 dataZoom: { show: true, title: { zoom: '区域缩放', back: '区域缩放还原' } },
1207                                 saveAsImage: { show: true }
1208                             }
1209                         },
1210                         xAxis: 
1211                             {
1212 
1213                             type: 'category',
1214                             boundaryGap: false,
1215                             data: result.cjrqList,
1216 
1217                              },
1218                         
1219                             
1220                         yAxis:[
1221                            {
1222                                name: '价格(元/千克)',
1223                                nameLocation: 'end',
1224                                 type: 'value',
1225                                 min: function (value) {
1226                                     return Math.floor(value.min - 0.1);
1227                                 },
1228                                 axisLabel: {
1229                                     formatter: '{value} '
1230                                 }
1231                            },
1232                            {
1233                                name: '交易量(吨)',
1234                                nameLocation: 'end',
1235                                type: 'value',
1236                                inverse:false,
1237                                
1238                            }
1239                         ],
1240 
1241                         series: [
1242                             {
1243                                 name: '田头价格',
1244                                 type: 'line',
1245                                 data: result.ttjgList,
1246                                 connectNulls: true
1247 
1248                             },
1249                             {
1250                                 name: '批发价格',
1251                                 type: 'line',
1252                                 data: result.pfjgList,
1253                                 connectNulls: true
1254                             },
1255 
1256                             {
1257                                 name: '零售价格',
1258                                 type: 'line',
1259                                 data: result.lsjgList,
1260                                 connectNulls: true
1261                             },
1262                             {
1263                                 name: '交易量',
1264                                 type: 'line',
1265                                 yAxisIndex:1,
1266                                 data: result.jylList,
1267                                 connectNulls: true
1268                             },
1269 
1270                         ],
1271                         tooltip: {
1272                             trigger: 'axis',
1273                             formatter: function (data) {
1274 
1275                                 var seriesNames = [];
1276                                 var formateStrings = [];
1277                                 var formateString = "";
1278                                 // console.log(typeof (data));
1279                                 formateStrings.push(data[0].name);
1280                                 if (data.length != undefined) {
1281 
1282                                     for (var i in data) {
1283                                         var item = data[i];
1284                                         if (item.data == null || item.data == "-") {
1285                                         }
1286                                         else {
1287                                             if (seriesNames.indexOf(item.seriesName) < 0) {
1288                                                 seriesNames.push(item.seriesName);
1289                                                 formateStrings.push(item.marker + item.seriesName + ": " + item.data.toFixed(2));
1290                                             }
1291                                         }
1292                                     }
1293                                 }
1294                                 else {
1295                                     var item = data;
1296                                     if (item.data == null || item.data == "-") {
1297                                     }
1298                                     else {
1299                                         if (!seriesNames.contains(item.seriesName)) {
1300                                             seriesNames.push(item.seriesName);
1301                                             formateStrings.push(item.marker + item.seriesName + ": " + item.data.toFixed(2));
1302                                         }
1303                                     }
1304                                 }
1305                                 formateString = formateStrings.join("<br />");
1306                                 return formateString;
1307                             }
1308                         }
1309                     })
1310                 });
1311             }
1312         }
1313         // 使用刚指定的配置项和数据显示图表。
1314         if (option && typeof option === "object") {
1315             chart_someTimePrice_line.setOption(option, true);
1316 
1317         }
1318 
1319         
1320         //价格预测和实际数据比较 按周
1321         var chart_WeekPrice_line = echarts.init(document.getElementById('weekPrice'));
1322         option = {
1323             title: {
1324                 text: '周均价格走势图',
1325                 left: "center",
1326             },
1327             tooltip: {
1328                 trigger: 'axis'
1329             },
1330             legend: {
1331                 data: ['田头价格', '批发价格', '零售价格','交易量'],
1332                 top: '30px',
1333             },
1334             //    color: ['#c23531', '#2f4554', '#61a0a8', '#c23531', '#2f4554', '#61a0a8'],
1335             grid: {
1336                 left: '3%',
1337                 right: '4%',
1338                 bottom: '3%',
1339                 containLabel: true
1340             },
1341             toolbox: {
1342                 right: '20px',
1343                 feature: {
1344 
1345                     dataZoom: { show: true, title: { zoom: '区域缩放', back: '区域缩放还原' } },
1346 
1347                     saveAsImage: { show: true }
1348                 }
1349             },
1350             xAxis: {
1351                 type: 'category',
1352                 boundaryGap: false,
1353                 data: [],
1354 
1355             },
1356             yAxis: {
1357                 type: 'value',
1358                 axisLabel: {
1359                     formatter: '{value}'
1360                 }
1361             },
1362             series: [
1363                 {
1364                     name: '田头价格',
1365                     type: 'line',
1366                     data: [],
1367                 },
1368                 {
1369                     name: '批发价格',
1370                     type: 'line',
1371                     data: [],
1372                 },
1373                 {
1374                     name: '零售价格',
1375                     type: 'line',
1376                     data: [],
1377                 },
1378 
1379             ]
1380         };
1381         // 使用刚指定的配置项和数据显示图表。
1382         if (option && typeof option === "object") {
1383             chart_WeekPrice_line.setOption(option, true);
1384         }
1385 
1386 
1387         //周均价格  异步加载数据
1388         function WeekPriceCompareLineAJAXData(locationSelect, productSelect, yearStartSelect_Week, weekStartSelect, yearEndSelect_Week, weekEndSelect) {
1389             var url = "@Url.Action("WeekPriceLineAJAXData")";
1390             if (locationSelect && productSelect && yearStartSelect_Week && weekStartSelect && yearEndSelect_Week && weekEndSelect) {
1391                 $.post(url, { yjxzqid: locationSelect, ncpid: productSelect, yearStart: yearStartSelect_Week, weekStart: weekStartSelect, yearEnd: yearEndSelect_Week, weekEnd: weekEndSelect }, function (result) {
1392 
1393 
1394                     chart_WeekPrice_line.setOption({
1395                         title: {
1396                             text: productSelectName + '周均价格走势图',
1397                             left: "center", 
1398                         },
1399                         legend: {
1400                             data: ['田头价格', '批发价格', '零售价格','交易量'],
1401                             top: '30px',
1402                         },             
1403                         //    color: ['#c23531', '#2f4554', '#61a0a8','#c23531', '#2f4554', '#61a0a8'],
1404                         grid: {
1405                             left: '3%',
1406                             right: '4%',
1407                             bottom: '3%',
1408                             containLabel: true
1409                         },
1410                         toolbox: {
1411                             right: '20px',
1412                             feature: {
1413   
1414                                 dataZoom: { show: true, title: { zoom: '区域缩放', back: '区域缩放还原' } },
1415 
1416                                 saveAsImage: { show: true }
1417                             }
1418                         },
1419 
1420                         xAxis: [
1421                             {
1422                                 type: 'category',
1423                                 boundaryGap: false,
1424                                 data: result.weekList,
1425                             },
1426 
1427                         ],
1428                         yAxis: [
1429                                {
1430                                    name: '价格(元/千克)',
1431                                    nameLocation: 'end',
1432                                    type: 'value',
1433 
1434                                    axisLabel: {
1435                                        formatter: '{value}'
1436                                    }
1437                                },
1438                                {
1439                                    name: '交易量(吨)',
1440                                    nameLocation: 'end',
1441                                    type: 'value',
1442                                    inverse: false,
1443 
1444                                }
1445                         ],
1446                         series: [
1447                             {
1448                                 name: '田头价格',
1449                                 type: 'line',
1450                                 data: result.ttjgList,
1451                                 connectNulls: true
1452    
1453                             },
1454                             {
1455                                 name: '批发价格',
1456                                 type: 'line',
1457                                 data: result.pfjgList,
1458                                 connectNulls: true
1459      
1460                             },
1461                             {
1462                                 name: '零售价格',
1463                                 type: 'line',
1464                                 data: result.lsjgList,
1465                                 connectNulls: true
1466      
1467                             },
1468                             {
1469                                 name: '交易量',
1470                                 type: 'line',
1471                                 yAxisIndex: 1,
1472                                 data: result.jylList,
1473                                 connectNulls: true
1474                             },
1475 
1476                         ],
1477                         tooltip: {
1478                             trigger: 'axis',
1479                             formatter: function (data) {
1480 
1481                                 var seriesNames = [];
1482                                 var formateStrings = [];
1483                                 var formateString = "";
1484                                 // console.log(typeof (data));
1485                                 formateStrings.push(data[0].name);
1486                                 if (data.length != undefined) {
1487 
1488                                     for (var i in data) {
1489                                         var item = data[i];
1490                                         if (item.data == null || item.data == "-") {
1491                                         }
1492                                         else {
1493                                             if (seriesNames.indexOf(item.seriesName) < 0) {
1494                                                 seriesNames.push(item.seriesName);
1495                                                 formateStrings.push(item.marker + item.seriesName + ": " + item.data.toFixed(2));
1496                                             }
1497                                         }
1498                                     }
1499                                 }
1500                                 else {
1501                                     var item = data;
1502                                     if (item.data == null || item.data == "-") {
1503                                     }
1504                                     else {
1505                                         if (!seriesNames.contains(item.seriesName)) {
1506                                             seriesNames.push(item.seriesName);
1507                                             formateStrings.push(item.marker + item.seriesName + ": " + item.data.toFixed(2));
1508                                         }
1509                                     }
1510                                 }
1511                                 formateString = formateStrings.join("<br />");
1512                                 return formateString;
1513                             }
1514                         }
1515                     });
1516                 });
1517             }
1518         }
1519 
1520 
1521 
1522         //月均价格行情曲线(第二排右侧)
1523         var chart_MonthPrice_line = echarts.init(document.getElementById('monthPrice'));
1524         option = {
1525             title: {
1526                 text: '月均价格走势图',
1527                 left: "center",
1528             },
1529             legend: {
1530                 data: ['田头价格', '批发价格', '零售价格'],
1531                 top: '30px',
1532             },
1533             tooltip: {
1534                 trigger: 'axis'
1535             },
1536             grid: {
1537                 left: '3%',
1538                 right: '4%',
1539                 bottom: '3%',
1540                 containLabel: true
1541             },
1542             toolbox: {
1543                 right: '20px',
1544                 feature: {
1545                     dataZoom: { show: true, title: { zoom: '区域缩放', back: '区域缩放还原' } },
1546                     saveAsImage: { show: true }
1547                 }
1548             },
1549             xAxis: {
1550                 type: 'category',
1551                 boundaryGap: false,
1552                 data: [],
1553 
1554             },
1555             yAxis: {
1556                 name: '价格(元/千克)',
1557                 type: 'value',
1558                 axisLabel: {
1559                     formatter: '{value} '
1560                 }
1561             },
1562             series: [
1563                 {
1564                     name: '田头价格',
1565                     type: 'line',
1566                     data: [],
1567                 },
1568                 {
1569                     name: '批发价格',
1570                     type: 'line',
1571                     data: [],
1572                 },
1573                 {
1574                     name: '零售价格',
1575                     type: 'line',
1576                     data: [],
1577                 },
1578 
1579             ]
1580         };
1581         //  异步加载数据
1582         function MonthPriceLineAJAXData(locationSelect, productSelect, yearStartSelect, monthStartSelect, yearEndSelect, monthEndSelect) {
1583             var url = "@Url.Action("MonthPriceLineAJAXData")";
1584             if (locationSelect && productSelect && yearStartSelect && monthStartSelect && yearEndSelect && monthEndSelect) {
1585                 $.post(url, { yjxzqid: locationSelect, ncpid: productSelect, yearStart: yearStartSelect, monthStart: monthStartSelect, yearEnd: yearEndSelect, monthEnd: monthEndSelect }, function (result) {
1586 
1587                     chart_MonthPrice_line.setOption({
1588                         title: {
1589                             text:productSelectName+ '月均价格走势图',
1590                             left: "center",
1591                         },
1592                         legend: {
1593                             data: ['田头价格', '批发价格', '零售价格','交易量'],
1594                             top: '30px',
1595                         },
1596                         grid: {
1597                             left: '3%',
1598                             right: '4%',
1599                             bottom: '3%',
1600                             containLabel: true
1601                         },
1602                         toolbox: {
1603                             right: '20px',
1604                             feature: {
1605                                 dataZoom: { show: true, title: { zoom: '区域缩放', back: '区域缩放还原' } },
1606                                 saveAsImage: { show: true }
1607                             }
1608                         },
1609                         xAxis: [
1610                             {
1611                                 type: 'category',
1612                                 boundaryGap: false,
1613                                 data: result.monthList,
1614                             },
1615 
1616                         ],
1617                         yAxis: [{
1618                             name:'价格(元/千克)',
1619                             type: 'value',
1620                             axisLabel: {
1621                                 formatter: '{value} '
1622                             }
1623                         },  
1624                         {
1625                             name: '交易量(吨)',
1626                             nameLocation: 'end',
1627                             type: 'value',
1628                             inverse:false,
1629                                
1630                         }],
1631                         series: [
1632                             {
1633                                 name: '田头价格',
1634                                 type: 'line',
1635                                 data: result.ttjgList,
1636                                 connectNulls: true
1637                             },
1638                             {
1639                                 name: '批发价格',
1640                                 type: 'line',
1641                                 data: result.pfjgList,
1642                                 connectNulls: true
1643                             },
1644                             {
1645                                 name: '零售价格',
1646                                 type: 'line',
1647                                 data: result.lsjgList,
1648                                 connectNulls: true
1649                             },
1650                             {
1651                                 name: '交易量',
1652                                 type: 'line',
1653                                 yAxisIndex: 1,
1654                                 data: result.jylList,
1655                                 connectNulls: true
1656                             },
1657 
1658                         ],
1659                         tooltip: {
1660                             trigger: 'axis',
1661                             formatter: function (data) {
1662 
1663                                 var seriesNames = [];
1664                                 var formateStrings = [];
1665                                 var formateString = "";
1666                                 // console.log(typeof (data));
1667                                 formateStrings.push(data[0].name);
1668                                 if (data.length != undefined) {
1669 
1670                                     for (var i in data) {
1671                                         var item = data[i];
1672                                         if (item.data == null || item.data == "-") {
1673                                         }
1674                                         else {
1675                                             if (seriesNames.indexOf(item.seriesName) < 0) {
1676                                                 seriesNames.push(item.seriesName);
1677                                                 formateStrings.push(item.marker + item.seriesName + ": " + item.data.toFixed(2));
1678                                             }
1679                                         }
1680                                     }
1681                                 }
1682                                 else {
1683                                     var item = data;
1684                                     if (item.data == null || item.data == "-") {
1685                                     }
1686                                     else {
1687                                         if (!seriesNames.contains(item.seriesName)) {
1688                                             seriesNames.push(item.seriesName);
1689                                             formateStrings.push(item.marker + item.seriesName + ": " + item.data.toFixed(2));
1690                                         }
1691                                     }
1692                                 }
1693                                 formateString = formateStrings.join("<br />");
1694                                 return formateString;
1695                             }
1696                         }
1697                     });
1698                 });
1699             }
1700         }
1701         // 使用刚指定的配置项和数据显示图表。
1702         if (option && typeof option === "object") {
1703             chart_MonthPrice_line.setOption(option, true);
1704         }
1705 
1706         //同一地区不同品种柱状图
1707         var chart_regionProductsPrice_bar = echarts.init(document.getElementById('regionProductsPrice'));
1708         option = {
1709             title: {
1710                 text: '同一地区不同品种柱状图',
1711                 left: "center",
1712             },
1713             tooltip: {
1714                 trigger: 'axis'
1715             },
1716             legend: {
1717                 data: ['田头价格', '批发价格', '零售价格'],
1718                 top: 30
1719             },
1720             grid: {
1721                 left: '3%',
1722                 right: '4%',
1723                 bottom: '3%',
1724                 containLabel: true
1725             },
1726             toolbox: {
1727                 right: '20px',
1728                 feature: {
1729                     dataZoom: { show: true, title: { zoom: '区域缩放', back: '区域缩放还原' } },
1730                     saveAsImage: { show: true }
1731                 }
1732             },
1733             calculable: true,
1734             xAxis: [
1735                 {
1736                     type: 'category',
1737                     data: []
1738                 }
1739             ],
1740             yAxis: [
1741                 {
1742                     type: 'value',
1743                     axisLabel: {
1744                         formatter: '{value} '
1745                     }
1746                 }
1747             ],
1748             series: [
1749                 {
1750                     name: '田头价格',
1751                     type: 'bar',
1752                     data: [],
1753 
1754                 },
1755                 {
1756                     name: '批发价格',
1757                     type: 'bar',
1758                     data: [],
1759 
1760                 },
1761                 {
1762                     name: '零售价格',
1763                     type: 'bar',
1764                     data: [],
1765 
1766                 },
1767             ]
1768         };
1769 
1770         // 异步数据加载
1771         function RegionProductsPriceBarAJAXData(yjxzqidSelect, ncpidSelect, selectDate) {
1772 
1773             var url = "@Url.Action("RegionProductsPriceBarAJAXData")";
1774             if (yjxzqidSelect && ncpidSelect && selectDate) {
1775                 $.post(url, { yjxzqid: yjxzqidSelect, ncpid: ncpidSelect, date: selectDate }, function (result) {
1776                     chart_regionProductsPrice_bar.setOption({
1777                         title: {
1778                             text:locationSelectName+ '感兴趣品种价格柱状图',
1779                             left: "center",
1780                         },
1781                         tooltip: {
1782                             trigger: 'axis',
1783                             formatter: function (data) {
1784 
1785                                 var seriesNames = [];
1786                                 var formateStrings = [];
1787                                 var formateString = "";
1788                                 // console.log(typeof (data));
1789                                 formateStrings.push(data[0].name);
1790                                 if (data.length != undefined) {
1791 
1792                                     for (var i in data) {
1793                                         var item = data[i];
1794                                         if (item.data == null || item.data == "-") {
1795                                         }
1796                                         else {
1797                                             if (seriesNames.indexOf(item.seriesName) < 0) {
1798                                                 seriesNames.push(item.seriesName);
1799                                                 formateStrings.push(item.marker + item.seriesName + ": " + item.data.toFixed(2));
1800                                             }
1801                                         }
1802                                     }
1803                                 }
1804                                 else {
1805                                     var item = data;
1806                                     if (item.data == null || item.data == "-") {
1807                                     }
1808                                     else {
1809                                         if (!seriesNames.contains(item.seriesName)) {
1810                                             seriesNames.push(item.seriesName);
1811                                             formateStrings.push(item.marker + item.seriesName + ": " + item.data.toFixed(2));
1812                                         }
1813                                     }
1814                                 }
1815                                 formateString = formateStrings.join("<br />");
1816                                 return formateString;
1817                             }
1818                         },
1819                         legend: {
1820                             data: ['田头价格', '批发价格', '零售价格','交易量'],
1821                             top: 30
1822                         },
1823                         grid: {
1824                             left: '3%',
1825                             right: '4%',
1826                             bottom: '3%',
1827                             containLabel: true
1828                         },
1829                         toolbox: {
1830                             right: '20px',
1831                             feature: {
1832                                 dataZoom: { show: true, title: { zoom: '区域缩放', back: '区域缩放还原' } },
1833                                 saveAsImage: { show: true }
1834                             }
1835                         },
1836                         calculable: true,
1837                         xAxis: [
1838                             {
1839                                 type: 'category',
1840                                 data: result.ncpmcList,
1841                             }
1842                         ],
1843                         yAxis: [
1844                             {
1845                                 name:'价格(元/千克)',
1846                                 type: 'value',
1847                                 axisLabel: {
1848                                     formatter: '{value} '
1849                                 }
1850                             },
1851                             {
1852                                 name: '交易量(吨)',
1853                                 nameLocation: 'end',
1854                                 type: 'value',
1855                                 inverse: false,
1856 
1857                             }
1858                         ],
1859                         series: [
1860                             {
1861                                 name: '田头价格',
1862                                 type: 'bar',
1863                                 data: result.ttjgList,
1864 
1865                             },
1866                             {
1867                                 name: '批发价格',
1868                                 type: 'bar',
1869                                 data: result.pfjgList,
1870 
1871                             },
1872                             {
1873                                 name: '零售价格',
1874                                 type: 'bar',
1875                                 data: result.lsjgList,
1876 
1877                             },
1878                             {
1879                                 name: '交易量',
1880                                 type: 'bar',
1881                                 yAxisIndex: 1,
1882                                 data: result.jylList,
1883                                 connectNulls: true
1884                             },
1885 
1886                         ]
1887                     });
1888                 });
1889             }
1890         }
1891         // 使用刚指定的配置项和数据显示图表。
1892         if (option && typeof option === "object") {
1893             chart_regionProductsPrice_bar.setOption(option, true);
1894 
1895         }
1896 
1897         //同一品种不同地区的价格柱状图
1898         var chart_productRegionsPrice_bar = echarts.init(document.getElementById('productRegionsPrice'));
1899         option = {
1900             title: {
1901                 text: '同一品种不同地区的价格柱状图',
1902                 left: "center",
1903             },
1904             tooltip: {
1905                 trigger: 'axis'
1906             },
1907             legend: {
1908                 data: ['田头价格', '批发价格', '零售价格'],
1909                 top: 30
1910             },
1911             grid: {
1912                 left: '3%',
1913                 right: '4%',
1914                 bottom: '3%',
1915                 containLabel: true
1916             },
1917             toolbox: {
1918                 right: '20px',
1919                 feature: {
1920                     dataZoom: { show: true, title: { zoom: '区域缩放', back: '区域缩放还原' } },
1921                     saveAsImage: { show: true }
1922                 }
1923             },
1924             calculable: true,
1925             xAxis: [
1926                 {
1927                     type: 'category',
1928                     data: []
1929                 }
1930             ],
1931             yAxis: [
1932                 {
1933                     type: 'value',
1934                     axisLabel: {
1935                         formatter: '{value} '
1936                     }
1937                 }
1938             ],
1939             series: [
1940                 {
1941                     name: '田头价格',
1942                     type: 'bar',
1943                     data: [],
1944 
1945                 },
1946                 {
1947                     name: '批发价格',
1948                     type: 'bar',
1949                     data: [],
1950 
1951                 },
1952                 {
1953                     name: '零售价格',
1954                     type: 'bar',
1955                     data: [],
1956 
1957                 },
1958             ]
1959         };
1960 
1961         // 异步数据加载
1962         function ProductRegionsPriceBarAJAXData(yjxzqidSelect, ncpidSelect, selectDate) {
1963 
1964             var url = "@Url.Action("ProductRegionsPriceBarAJAXData")";
1965             if (yjxzqidSelect && ncpidSelect && selectDate) {
1966                 $.post(url, { yjxzqid: yjxzqidSelect, ncpid: ncpidSelect, date: selectDate }, function (result) {
1967                     chart_productRegionsPrice_bar.setOption({
1968                         title: {
1969                             text: '感兴趣地区' + productSelectName + '价格柱状图',
1970                             left: "center",
1971                         },
1972                         tooltip: {
1973                             trigger: 'axis',
1974                             formatter: function (data) {
1975 
1976                                 var seriesNames = [];
1977                                 var formateStrings = [];
1978                                 var formateString = "";
1979                                 // console.log(typeof (data));
1980                                 formateStrings.push(data[0].name);
1981                                 if (data.length != undefined) {
1982 
1983                                     for (var i in data) {
1984                                         var item = data[i];
1985                                         if (item.data == null || item.data == "-") {
1986                                         }
1987                                         else {
1988                                             if (seriesNames.indexOf(item.seriesName) < 0) {
1989                                                 seriesNames.push(item.seriesName);
1990                                                 formateStrings.push(item.marker + item.seriesName + ": " + item.data.toFixed(2));
1991                                             }
1992                                         }
1993                                     }
1994                                 }
1995                                 else {
1996                                     var item = data;
1997                                     if (item.data == null || item.data == "-") {
1998                                     }
1999                                     else {
2000                                         if (!seriesNames.contains(item.seriesName)) {
2001                                             seriesNames.push(item.seriesName);
2002                                             formateStrings.push(item.marker + item.seriesName + ": " + item.data.toFixed(2));
2003                                         }
2004                                     }
2005                                 }
2006                                 formateString = formateStrings.join("<br />");
2007                                 return formateString;
2008                             }
2009                         },
2010                         legend: {
2011                             data: ['田头价格', '批发价格', '零售价格','交易量'],
2012                             top: 30
2013                         },
2014                         grid: {
2015                             left: '3%',
2016                             right: '4%',
2017                             bottom: '3%',
2018                             containLabel: true
2019                         },
2020                         toolbox: {
2021                             right: '20px',
2022                             feature: {
2023                                 dataZoom: { show: true, title: { zoom: '区域缩放', back: '区域缩放还原' } },
2024                                 saveAsImage: { show: true }
2025                             }
2026                         },
2027                         calculable: true,
2028                         xAxis: [
2029                             {
2030                                 type: 'category',
2031                                 data: result.yjxzqnameList,
2032                             }
2033                         ],
2034                         yAxis: [
2035                             {
2036                                 name: '价格(元/千克)',
2037                                 type: 'value',
2038                                 axisLabel: {
2039                                     formatter: '{value} '
2040                                 }
2041                             },
2042                             {
2043                                 name: '交易量(吨)',
2044                                 nameLocation: 'end',
2045                                 type: 'value',
2046                                 inverse: false,
2047 
2048                             }
2049                         ],
2050                         series: [
2051                             {
2052                                 name: '田头价格',
2053                                 type: 'bar',
2054                                 data: result.ttjgList,
2055 
2056                             },
2057                             {
2058                                 name: '批发价格',
2059                                 type: 'bar',
2060                                 data: result.pfjgList,
2061 
2062                             },
2063                             {
2064                                 name: '零售价格',
2065                                 type: 'bar',
2066                                 data: result.lsjgList,
2067 
2068                             },
2069                             {
2070                                 name: '交易量',
2071                                 type: 'bar',
2072                                 yAxisIndex: 1,
2073                                 data: result.jylList,
2074                                 connectNulls: true
2075                             },
2076                         ]
2077                     });
2078                 });
2079             }
2080         }
2081         // 使用刚指定的配置项和数据显示图表。
2082         if (option && typeof option === "object") {
2083             chart_productRegionsPrice_bar.setOption(option, true);
2084 
2085         }
2086 
2087         window.onresize = function () {
2088             setTimeout("chartResize();", 100);
2089         }
2090         function chartResize() {
2091             $("#gridJghq").datagrid("resize");
2092             $("#identicalProductDifferentRegions").datagrid("resize");
2093             $("#someTimePriceForm").datagrid("resize");
2094             $("#weekPriceListGrid").datagrid("resize");
2095             $("#monthlyPriceListGrid").datagrid("resize");
2096 
2097             chart_someTimePrice_line.resize();
2098             chart_MonthPrice_line.resize();
2099             chart_WeekPrice_line.resize();
2100             chart_regionProductsPrice_bar.resize();
2101             chart_productRegionsPrice_bar.resize();
2102         }
2103 
2104     </script>

View Code

服务器端(C#):

api类

Echarts 数据视图 生成Excel的方法 Echarts 数据视图 生成Excel的方法

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Vegetable.DAL;
using Vegetable.DBHelper;
using Vegetable.Models;

namespace Vegetable.Controllers
{
    public class JghqController : JsonController
    {
        DAL.lyc2Entities db = new Vegetable.DAL.lyc2Entities();

        #region 价格行情-需求变更

        #region 蔬菜价格查询

        /// <summary>
        ///  本站使用
        /// </summary>
        /// <returns></returns>
        public ActionResult SCjgcx()
        {
            return View();
        }

        /// <summary>
        ///  部分页 公用
        /// </summary>
        /// <returns></returns>
        public ActionResult SCjgcxPartial()
        {
            //var model = "我是Model";
            //return View("SCjgcxPartial",model);
            return PartialView();
        }

        /// <summary>
        ///  站外使用 
        /// </summary>
        /// <returns></returns>
        public ActionResult SCjgcxPage()
        {

            return View();
        }

        #endregion


        #region 蔬菜价格比较
        public ActionResult SCjgbj()
        {
            return View();
        }

        public ActionResult SCjgbjPartial()
        {
            return PartialView();
        }

        public ActionResult SCjgbjPage()
        {
            return View();
        }
        #endregion


        #region 生猪价格查询
        public ActionResult SZjgcx()
        {
            return View();
        }
        /// <summary>
        ///  部分页 公用
        /// </summary>
        /// <returns></returns>
        public ActionResult SZjgcxPartial()
        {

            return PartialView();
        }

        /// <summary>
        ///  站外使用 
        /// </summary>
        /// <returns></returns>
        public ActionResult SZjgcxPage()
        {

            return View();
        }

        #endregion

        #region 生猪价格比较
        public ActionResult SZjgbj()
        {
            return View();
        }

        public ActionResult SZjgbjPartial()
        {
            return PartialView();
        }

        public ActionResult SZjgbjPage()
        {
            return View();
        }
        #endregion


      

        #endregion


        // GET: Jghq
        public ActionResult Index()
        {
            return View();
        }

        /// <summary>
        /// 同一地区不同品种价格表
        /// </summary>
        /// <param name="page"></param>
        /// <param name="rows"></param>
        /// <param name="sort"></param>
        /// <param name="order"></param>
        /// <param name="date"></param>
        /// <param name="products"></param>
        /// <param name="regions"></param>
        /// <returns></returns>
        public JsonResult yjdatealljg(int page,int rows, string sort, string order,DateTime? date, string products, string regions)
        {
            PageModel pageModel = new PageModel();
            pageModel.Page = page;
            pageModel.Rows = rows;
            pageModel.Order = order;
            pageModel.Sort = sort;

            return yjdatealljg(pageModel, date, products, regions);
        }

       
        [HttpPost]
        public JsonResult yjdatealljg(PageModel pageInfo, DateTime? date, string products, string regions)
        {
            ResultModel result = new ResultModel();

            if (pageInfo.Page <= 0)
            {
                pageInfo.Page = 1;
            }
            if (pageInfo.Rows <= 0)
            {
                pageInfo.Rows = 20;
            }
            var data = db.v_yjdatealljg.Select(d => new {
               ncpid= d.ncpid,
               ncpmc= d.ncpmc,
               yjxzqid= d.yjxzqid,
               yjxzqname= d.yjxzqname,             
               cjrq= d.cjrq,
               ttjg= d.ttjg,
               pfjg= d.pfjg,
               lsjg= d.lsjg,
               jyl=d.jyl


            });
            
            if (pageInfo.FilterRuleList != null)
            {
                data = data.Where(pageInfo.FilterRuleList.ToArray());
            }

            if (date == null || ((DateTime)date).Year < 2000)
            {
                //测试用例
               // var now = DateTime.Parse("2016-06-15");
                var now = DateTime.Now;
                date = now.AddDays(-1); //近1天(昨天)
                
            }
            data = data.Where(d => d.cjrq == date);
            var pids = new List<int>();
            var rids = new List<int>();
            if (products == null) products = "";
            if (regions == null) regions = "";
            var productIds = products.Split(',');
            var regionIds = regions.Split(',');
            foreach (var pid in productIds)
            {
                if (pid == "")
                {
                    continue;
                }
                pids.Add(Convert.ToInt32(pid));
            }
            foreach(var rid in regionIds)
            {
                if (rid == "")
                {
                    continue;
                }
                rids.Add(Convert.ToInt32(rid));
            }
            data = data.Where(d => pids.Contains(d.ncpid) && rids.Contains(d.yjxzqid));
            if (pageInfo.Sort != null)
            {
                string[] sorts = pageInfo.Sort.Split(',');
                string[] orderbys = pageInfo.Order.Split(',');
                List<bool> isAscs = new List<bool>();
                foreach (var o in orderbys)
                {
                    isAscs.Add(o == "asc");
                }
                data = data.OrderBy(sorts, isAscs.ToArray());

            }
            else
            {
                data = data.OrderBy(d => d.cjrq);
            }

            result.rows = data.Skip((pageInfo.Page - 1) * pageInfo.Rows).Take(pageInfo.Rows).ToList();
            result.total = data.Count();

            result.success = true;
            return Json(result, JsonRequestBehavior.AllowGet);
        }

        
        /// <summary>
        /// 同一品种不同地区价格表
        /// </summary>
        /// <param name="page"></param>
        /// <param name="rows"></param>
        /// <param name="sort"></param>
        /// <param name="order"></param>
        /// <param name="date"></param>
        /// <param name="products"></param>
        /// <param name="regions"></param>
        /// <returns></returns>
        public JsonResult IdenticalProductDifferentRegionsAjaxData(int page, int rows, string sort, string order, DateTime? date, string products, string regions)
        {
            PageModel pageModel = new PageModel();
            pageModel.Page = page;
            pageModel.Rows = rows;
            pageModel.Order = order;
            pageModel.Sort = sort;

            return IdenticalProductDifferentRegionsAjaxData(pageModel, date, products, regions);
        }


        [HttpPost]
        public JsonResult IdenticalProductDifferentRegionsAjaxData(PageModel pageInfo, DateTime? date, string products, string regions)
        {
            ResultModel result = new ResultModel();

            if (pageInfo.Page <= 0)
            {
                pageInfo.Page = 1;
            }
            if (pageInfo.Rows <= 0)
            {
                pageInfo.Rows = 20;
            }
            var data = db.v_yjdatealljg.Select(d => new {
                ncpid = d.ncpid,
                ncpmc = d.ncpmc,
                yjxzqid = d.yjxzqid,
                yjxzqname = d.yjxzqname,
                cjrq = d.cjrq,
                ttjg = d.ttjg,
                pfjg = d.pfjg,
                lsjg = d.lsjg,
                jyl = d.jyl

            });

            if (pageInfo.FilterRuleList != null)
            {
                data = data.Where(pageInfo.FilterRuleList.ToArray());
            }

            if (date == null || ((DateTime)date).Year < 2000)
            {
                //测试用例
                // var now = DateTime.Parse("2016-06-15");
                var now = DateTime.Now;
                date = now.AddDays(-1); //近1天(昨天)

            }
            data = data.Where(d => d.cjrq == date);
            var pids = new List<int>();
            var rids = new List<int>();
            if (products == null) products = "";
            if (regions == null) regions = "";
            var productIds = products.Split(',');
            var regionIds = regions.Split(',');
            foreach (var pid in productIds)
            {
                if (pid == "")
                {
                    continue;
                }
                pids.Add(Convert.ToInt32(pid));
            }
            foreach (var rid in regionIds)
            {
                if (rid == "")
                {
                    continue;
                }
                rids.Add(Convert.ToInt32(rid));
            }
            data = data.Where(d => pids.Contains(d.ncpid) && rids.Contains(d.yjxzqid));
            if (pageInfo.Sort != null)
            {
                string[] sorts = pageInfo.Sort.Split(',');
                string[] orderbys = pageInfo.Order.Split(',');
                List<bool> isAscs = new List<bool>();
                foreach (var o in orderbys)
                {
                    isAscs.Add(o == "asc");
                }
                data = data.OrderBy(sorts, isAscs.ToArray());

            }
            else
            {
                data = data.OrderBy(d => d.cjrq);
            }

            result.rows = data.Skip((pageInfo.Page - 1) * pageInfo.Rows).Take(pageInfo.Rows).ToList();
            result.total = data.Count();

            result.success = true;
            return Json(result, JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// 同一品种不同地区价格表
        /// </summary>
        /// <param name="page"></param>
        /// <param name="rows"></param>
        /// <param name="sort"></param>
        /// <param name="order"></param>
        /// <param name="date"></param>
        /// <param name="products"></param>
        /// <param name="regions"></param>
        /// <returns></returns>
        public JsonResult SZIdenticalProductDifferentRegionsAjaxData(int page, int rows, string sort, string order, DateTime? date, string products, string regions)
        {
            PageModel pageModel = new PageModel();
            pageModel.Page = page;
            pageModel.Rows = rows;
            pageModel.Order = order;
            pageModel.Sort = sort;

            return SZIdenticalProductDifferentRegionsAjaxData(pageModel, date, products, regions);
        }


        [HttpPost]
        public JsonResult SZIdenticalProductDifferentRegionsAjaxData(PageModel pageInfo, DateTime? date, string products, string regions)
        {
            ResultModel result = new ResultModel();

            if (pageInfo.Page <= 0)
            {
                pageInfo.Page = 1;
            }
            if (pageInfo.Rows <= 0)
            {
                pageInfo.Rows = 20;
            }
            var data = db.v_yjdatezrsjjg.Select(d => new {
                ncpid = d.ncpid,
                ncpmc = d.ncpmc,
                yjxzqid = d.yjxzqid,
                yjxzqname = d.yjxzqname,
                cjrq = d.cjrq,
                pfjg = d.pfjg,


            });

            if (pageInfo.FilterRuleList != null)
            {
                data = data.Where(pageInfo.FilterRuleList.ToArray());
            }

            if (date == null || ((DateTime)date).Year < 2000)
            {
                //测试用例
                // var now = DateTime.Parse("2016-06-15");
                var now = DateTime.Now;
                date = now.AddDays(-1); //近1天(昨天)

            }
            data = data.Where(d => d.cjrq == date);
            var pids = new List<int>();
            var rids = new List<int>();
            if (products == null) products = "";
            if (regions == null) regions = "";
            var productIds = products.Split(',');
            var regionIds = regions.Split(',');
            foreach (var pid in productIds)
            {
                if (pid == "")
                {
                    continue;
                }
                pids.Add(Convert.ToInt32(pid));
            }
            foreach (var rid in regionIds)
            {
                if (rid == "")
                {
                    continue;
                }
                rids.Add(Convert.ToInt32(rid));
            }
            data = data.Where(d => pids.Contains(d.ncpid) && rids.Contains(d.yjxzqid));
            if (pageInfo.Sort != null)
            {
                string[] sorts = pageInfo.Sort.Split(',');
                string[] orderbys = pageInfo.Order.Split(',');
                List<bool> isAscs = new List<bool>();
                foreach (var o in orderbys)
                {
                    isAscs.Add(o == "asc");
                }
                data = data.OrderBy(sorts, isAscs.ToArray());

            }
            else
            {
                data = data.OrderBy(d => d.cjrq);
            }

            result.rows = data.Skip((pageInfo.Page - 1) * pageInfo.Rows).Take(pageInfo.Rows).ToList();
            result.total = data.Count();

            result.success = true;
            return Json(result, JsonRequestBehavior.AllowGet);
        }


        /// <summary>
        ///  价格行情表
        /// </summary>
        /// <param name="page"></param>
        /// <param name="rows"></param>
        /// <param name="sort"></param>
        /// <param name="order"></param>
        /// <param name="products"></param>
        /// <param name="regions"></param>
        /// <param name="start"></param>
        /// <param name="end"></param>
        /// <param name=""></param>
        /// <returns></returns>
        public JsonResult SomeTimePriceFormDataAjax(int page, int rows, string sort, string order,  string products, string regions, DateTime? start, DateTime? end)
        {
            PageModel pageModel = new PageModel();
            pageModel.Page = page;
            pageModel.Rows = rows;
            pageModel.Order = order;
            pageModel.Sort = sort;

            return SomeTimePriceFormDataAjax(pageModel,  products, regions, start, end);
        }

        [HttpPost]
        public JsonResult SomeTimePriceFormDataAjax(PageModel pageInfo,  string products, string regions,DateTime? start, DateTime? end)
        {
            ResultModel result = new ResultModel();

            if (pageInfo.Page <= 0)
            {
                pageInfo.Page = 1;
            }
            if (pageInfo.Rows <= 0)
            {
                pageInfo.Rows = 20;
            }
            var data = db.v_yjdatealljg.Select(d => new {
                ncpid = d.ncpid,
                ncpmc = d.ncpmc,
                yjxzqid = d.yjxzqid,
                yjxzqname = d.yjxzqname,
                cjrq = d.cjrq,
                ttjg = d.ttjg,
                pfjg = d.pfjg,
                lsjg = d.lsjg,
                jyl=d.jyl

            });

            if (pageInfo.FilterRuleList != null)
            {
                data = data.Where(pageInfo.FilterRuleList.ToArray());
            }

            if (start == null || end==null||start>end ||((DateTime)end).Year < 2000)
            {
                //测试用例
                //start = DateTime.Parse("2016-06-19").AddDays(-30);
                //end = DateTime.Parse("2016-06-19").AddDays(-1);
                start = DateTime.Now.AddDays(-30);
                end = DateTime.Now.AddDays(-1);
            }

            data = data.Where(d => d.cjrq >=start&&d.cjrq<=end);



            var pids = new List<int>();
            var rids = new List<int>();
            if (products == null) products = "";
            if (regions == null) regions = "";
            var productIds = products.Split(',');
            var regionIds = regions.Split(',');
            foreach (var pid in productIds)
            {
                if (pid == "")
                {
                    continue;
                }
                pids.Add(Convert.ToInt32(pid));
            }
            foreach (var rid in regionIds)
            {
                if (rid == "")
                {
                    continue;
                }
                rids.Add(Convert.ToInt32(rid));
            }
            data = data.Where(d => pids.Contains(d.ncpid) && rids.Contains(d.yjxzqid));
            if (pageInfo.Sort != null)
            {
                string[] sorts = pageInfo.Sort.Split(',');
                string[] orderbys = pageInfo.Order.Split(',');
                List<bool> isAscs = new List<bool>();
                foreach (var o in orderbys)
                {
                    isAscs.Add(o == "asc");
                }
                data = data.OrderBy(sorts, isAscs.ToArray());

            }
            else
            {
                data = data.OrderBy(d => d.cjrq);
            }

            result.rows = data.Skip((pageInfo.Page - 1) * pageInfo.Rows).Take(pageInfo.Rows).ToList();
            result.total = data.Count();

            result.success = true;
            return Json(result, JsonRequestBehavior.AllowGet);
        }


        
        /// <summary>
        /// 月度价格行情表
        /// </summary>
        /// <param name="page">页码</param>
        /// <param name="rows">表格数据</param>
        /// <param name="sort"></param>
        /// <param name="order">排序</param>
        /// <param name="products"></param>
        /// <param name="regions"></param>
        /// <param name="yearStart"></param>
        /// <param name="monthStart"></param>
        /// <param name="yearEnd"></param>
        /// <param name="monthEnd"></param>
        /// <returns></returns>
        public JsonResult WeekPriceList(int page, int rows, string sort, string order, string products, string regions, int? yearStart, int? weekStart, int? yearEnd, int? weekEnd)
        {
            PageModel pageModel = new PageModel();
            pageModel.Page = page;
            pageModel.Rows = rows;
            pageModel.Order = order;
            pageModel.Sort = sort;

            return WeekPriceList(pageModel, products, regions, yearStart, weekStart, yearEnd, weekEnd);
        }
        [HttpPost]
        public JsonResult WeekPriceList(PageModel pageInfo, string products, string regions, int? yearStart, int? weekStart, int? yearEnd, int? weekEnd)
        {
            ResultModel result = new ResultModel();

            if (pageInfo.Page <= 0)
            {
                pageInfo.Page = 1;
            }
            if (pageInfo.Rows <= 0)
            {
                pageInfo.Rows = 20;
            }
            var data = db.v_yjweekalljg.Select(d => new
            {
                yjxzqid = d.yjxzqid,
                yjxzqname = d.yjxzqname,
                ncpid = d.ncpid,
                ncpmc = d.ncpmc,
                cjyear = d.cjyear,
                cjweek = d.cjweek,
                lsjg = d.lsjg,
                pfjg = d.pfjg,
                ttjg = d.ttjg,
                jyl = d.jyl
            }
            );
            if (pageInfo.FilterRuleList != null)
            {
                data = data.Where(pageInfo.FilterRuleList.ToArray());
            }

            //如果年月为空,默认显示近12个月
            //if (string.IsNullOrEmpty(yearStart.ToString()) || string.IsNullOrEmpty(weekStart.ToString()) || string.IsNullOrEmpty(yearStart.ToString()) || string.IsNullOrEmpty(weekEnd.ToString()))
            //{

            //    var now = DateTime.Now;
            //    DateTime start1 = new DateTime();
            //    start1 = now.AddMonths(-12);
            //    yearStart = start1.Year;
            //    weekStart = start1.Month;
            //    yearEnd = now.Year;
            //    weekEnd = now.Month;

            //}

            if (yearStart < yearEnd)
            {
                data = data.Where(d => ((d.cjyear == yearStart && d.cjweek >= weekStart) || (d.cjyear == yearEnd && d.cjweek <= weekEnd) || (d.cjyear > yearStart && d.cjyear < yearEnd)));
            }
            if (yearStart == yearEnd)
            {

                data = data.Where(d => ((d.cjyear == yearStart && d.cjweek >= weekStart && d.cjweek <= weekEnd)));
            }

            if (yearStart > yearEnd)
            {
                data = data.Where(d => (d.cjyear > yearStart && d.cjyear < yearEnd));
            }

            var pids = new List<int>();
            var rids = new List<int>();
            if (products == null) products = "";
            if (regions == null) regions = "";
            var productIds = products.Split(',');
            var regionIds = regions.Split(',');
            foreach (var pid in productIds)
            {
                if (pid == "")
                {
                    continue;
                }
                pids.Add(Convert.ToInt32(pid));
            }
            foreach (var rid in regionIds)
            {
                if (rid == "")
                {
                    continue;
                }
                rids.Add(Convert.ToInt32(rid));
            }
            data = data.Where(d => pids.Contains(d.ncpid) && rids.Contains(d.yjxzqid));

            if (pageInfo.Sort != null)
            {
                string[] sorts = pageInfo.Sort.Split(',');
                string[] orderbys = pageInfo.Order.Split(',');
                List<bool> isAscs = new List<bool>();
                foreach (var o in orderbys)
                {
                    isAscs.Add(o == "asc");
                }
                data = data.OrderBy(sorts, isAscs.ToArray());

            }
            else
            {
                data = data.OrderBy(d => d.cjyear).ThenBy(d => d.cjweek);

            }

            result.rows = data.Skip((pageInfo.Page - 1) * pageInfo.Rows).Take(pageInfo.Rows).ToList();
            result.total = data.Count();

            result.success = true;
            return Json(result, JsonRequestBehavior.AllowGet);
        }




        /// <summary>
        /// 月度价格行情表
        /// </summary>
        /// <param name="page">页码</param>
        /// <param name="rows">表格数据</param>
        /// <param name="sort"></param>
        /// <param name="order">排序</param>
        /// <param name="products"></param>
        /// <param name="regions"></param>
        /// <param name="yearStart"></param>
        /// <param name="monthStart"></param>
        /// <param name="yearEnd"></param>
        /// <param name="monthEnd"></param>
        /// <returns></returns>
        public JsonResult MonthlyPriceList(int page, int rows, string sort, string order,  string products, string regions, int? yearStart, int? monthStart, int? yearEnd, int? monthEnd)
        {
            PageModel pageModel = new PageModel();
            pageModel.Page = page;
            pageModel.Rows = rows;
            pageModel.Order = order;
            pageModel.Sort = sort;

            return MonthlyPriceList(pageModel, products, regions, yearStart, monthStart,yearEnd,  monthEnd);
        }
        [HttpPost]
        public JsonResult MonthlyPriceList(PageModel pageInfo, string products, string regions, int? yearStart, int? monthStart, int? yearEnd, int? monthEnd)
        {
            ResultModel result = new ResultModel();

            if (pageInfo.Page <= 0)
            {
                pageInfo.Page = 1;
            }
            if (pageInfo.Rows <= 0)
            {
                pageInfo.Rows = 20;
            }
            var data = db.v_yjmonthalljg.Select(d => new
            {
                yjxzqid = d.yjxzqid,
                yjxzqname = d.yjxzqname,
                ncpid = d.ncpid,
                ncpmc = d.ncpmc,
                cjyear = d.cjyear,
                cjmonth = d.cjmonth,
                lsjg = d.lsjg,
                pfjg = d.pfjg,
                ttjg = d.ttjg,
                jyl=d.jyl
            }
            );
            if (pageInfo.FilterRuleList != null)
            {
                data = data.Where(pageInfo.FilterRuleList.ToArray());
            }

            //如果年月为空,默认显示近12个月
            if (string.IsNullOrEmpty(yearStart.ToString()) || string.IsNullOrEmpty(monthStart.ToString()) || string.IsNullOrEmpty(yearStart.ToString()) || string.IsNullOrEmpty(monthEnd.ToString()))
            {

                var now = DateTime.Now;
                DateTime start1 = new DateTime();
                start1 = now.AddMonths(-12);
                yearStart = start1.Year;
                monthStart = start1.Month;
                yearEnd = now.Year;
                monthEnd = now.Month;

            }

            if (yearStart < yearEnd)
            {
                data = data.Where(d => ((d.cjyear == yearStart && d.cjmonth >= monthStart) || (d.cjyear == yearEnd && d.cjmonth <= monthEnd) || (d.cjyear > yearStart && d.cjyear < yearEnd)));
            }
            if (yearStart == yearEnd)
            {

                data = data.Where(d => ((d.cjyear == yearStart && d.cjmonth >= monthStart && d.cjmonth <= monthEnd)));
            }

            if (yearStart > yearEnd)
            {
                data = data.Where(d => (d.cjyear > yearStart && d.cjyear < yearEnd));
            }

            var pids = new List<int>();
            var rids = new List<int>();
            if (products == null) products = "";
            if (regions == null) regions = "";
            var productIds = products.Split(',');
            var regionIds = regions.Split(',');
            foreach (var pid in productIds)
            {
                if (pid == "")
                {
                    continue;
                }
                pids.Add(Convert.ToInt32(pid));
            }
            foreach (var rid in regionIds)
            {
                if (rid == "")
                {
                    continue;
                }
                rids.Add(Convert.ToInt32(rid));
            }
            data = data.Where(d => pids.Contains(d.ncpid) && rids.Contains(d.yjxzqid));

            if (pageInfo.Sort != null)
            {
                string[] sorts = pageInfo.Sort.Split(',');
                string[] orderbys = pageInfo.Order.Split(',');
                List<bool> isAscs = new List<bool>();
                foreach (var o in orderbys)
                {
                    isAscs.Add(o == "asc");
                }
                data = data.OrderBy(sorts, isAscs.ToArray());

            }
            else
            {
                data = data.OrderBy(d => d.cjyear).ThenBy(d => d.cjmonth);
              
            }

            result.rows = data.Skip((pageInfo.Page - 1) * pageInfo.Rows).Take(pageInfo.Rows).ToList();
            result.total = data.Count();

            result.success = true;
            return Json(result, JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// (选中品种一段日期的三种)价格行情曲线
        /// </summary>
        /// <returns></returns>
        public JsonResult SomeTimePriceLineAJAXData(int yjxzqid, int ncpid, DateTime start, DateTime end)
        {

            //测试用例
            //  yjxzqid = 9;  
            //  ncpid = 35;   

            var result = new EchartsModel();
            //如果为空,赋默认值
            if (start == null || end == null)
            {
                //测试用例
                //start = DateTime.Parse("2016-06-19").AddDays(-30 );
                //end = DateTime.Parse("2016-06-19").AddDays(-1);
                start = DateTime.Now.AddDays(-30);
                end = DateTime.Now.AddDays(-1);

            }

            //结束日期大于开始日期,结束日期小于今天
            if (end.Date >= start.Date )
            {

                V_yjdatealljgDal dal = new V_yjdatealljgDal();
                var data1 = dal.SelectList(yjxzqid,ncpid,start,end);
                result.lsjgList = data1.OrderBy(d => d.cjrq).Select(d => d.lsjg).ToList();
                result.pfjgList = data1.OrderBy(d => d.cjrq).Select(d => d.pfjg).ToList();
                result.ttjgList = data1.OrderBy(d => d.cjrq).Select(d => d.ttjg).ToList();
                result.cjrqList = data1.OrderBy(d => d.cjrq).Select(d => d.cjrq.ToString("yyyy-MM-dd")).ToList();
                result.jylList = data1.OrderBy(d => d.cjrq).Select(d => d.jyl).ToList();
            }


            return Json(result, JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// (选中品种一段日期的三种)价格行情曲线
        /// </summary>
        /// <returns></returns>
        public JsonResult SZSomeTimePriceLineAJAXData(int yjxzqid, int ncpid, DateTime start, DateTime end)
        {

            //测试用例
            //  yjxzqid = 9;  
            //  ncpid = 35;   

            var result = new EchartsModel();
            //如果为空,赋默认值
            if (start == null || end == null)
            {
                //测试用例
                //start = DateTime.Parse("2016-06-19").AddDays(-30 );
                //end = DateTime.Parse("2016-06-19").AddDays(-1);
                start = DateTime.Now.AddDays(-30);
                end = DateTime.Now.AddDays(-1);

            }

            //结束日期大于开始日期,结束日期小于今天
            if (end.Date >= start.Date)
            {

                var dal = new V_yjdatezrsjjgDal();
                var data1 = dal.SelectList(yjxzqid, ncpid, start, end);
                result.pfjgList = data1.OrderBy(d => d.cjrq).Select(d => d.pfjg).ToList();
                result.cjrqList = data1.OrderBy(d => d.cjrq).Select(d => d.cjrq.ToString("yyyy-MM-dd")).ToList();
            }


            return Json(result, JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        ///  周价格行情曲线
        /// </summary>
        /// <param name="yjxzqid">一级行政区id</param>
        /// <param name="ncpid">农产品id</param>
        /// <returns></returns>
        public JsonResult WeekPriceLineAJAXData(int yjxzqid, int ncpid, int yearStart, int weekStart, int yearEnd, int weekEnd)
        {
            V_yjweekalljgDal dal = new V_yjweekalljgDal();
            var result = new EchartsModel();




            //if (!string.IsNullOrEmpty(yjxzqid.ToString())&&!string.IsNullOrEmpty(ncpid.ToString())&& !string.IsNullOrEmpty(yearStart.ToString()) && !string.IsNullOrEmpty(weekStart.ToString()) && !string.IsNullOrEmpty(yearStart.ToString()) && !string.IsNullOrEmpty(weekEnd.ToString()))
            //{

            //var now = DateTime.Now;           
            //DateTime start1 = new DateTime();
            //start1 = now.AddMonths(-12); 
            //yearStart = start1.Year;
            //weekStart = start1.Month;
            //yearEnd = now.Year;
            //weekEnd = now.Month;

            //}else
            //{
            //    result = null;

            //}
            var data2 = dal.SelectList(yjxzqid, ncpid, yearStart, weekStart, yearEnd, weekEnd).OrderBy(d => d.cjyear).ThenBy(d => d.cjweek);

                //记录表数据
                result.lsjgList = data2.Select(d => d.lsjg).ToList();
                result.pfjgList = data2.Select(d => d.pfjg).ToList();
                result.ttjgList = data2.Select(d => d.ttjg).ToList();
                result.jylList = data2.Select(d => d.jyl).ToList();
               result.weekList = data2.Select(d => d.cjweek).ToList();//待删除

            //年周 转换为 n周(mm.dd – mm.dd)
            var weekAndYear = data2.Select(d => new { year = d.cjyear, week = d.cjweek }).ToList();
            var dateList = new List<string>() { };
            foreach (var item in weekAndYear)
            {
                var weekhelp3 = new WeekHelper((int)item.year, (int)item.week);
                dateList.Add("(" + weekhelp3.DateStart.ToString("MM.dd") + "-" + weekhelp3.DateEnd.ToString("MM.dd") + ") " + item.week);
            }

            result.weekListAndYear = dateList;

            return Json(result, JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        ///  周价格行情曲线
        /// </summary>
        /// <param name="yjxzqid">一级行政区id</param>
        /// <param name="ncpid">农产品id</param>
        /// <returns></returns>
        public JsonResult SZWeekPriceLineAJAXData(int yjxzqid, int ncpid, int yearStart, int weekStart, int yearEnd, int weekEnd)
        {
            var dal = new V_yjweekzrsjjgDal();
            var result = new EchartsModel();
            var data2 = dal.SelectList(yjxzqid, ncpid, yearStart, weekStart, yearEnd, weekEnd).OrderBy(d => d.cjyear).ThenBy(d => d.cjweek);
            //记录表数据
      
            result.pfjgList = data2.Select(d => d.pfjg).ToList();
            result.weekList = data2.Select(d => d.cjweek).ToList();//待删除
            //年周 转换为 n周(mm.dd – mm.dd)
            var weekAndYear = data2.Select(d => new { year = d.cjyear, week = d.cjweek }).ToList();
            var dateList = new List<string>() { };
            foreach (var item in weekAndYear)
            {
                var weekhelp3 = new WeekHelper((int)item.year, (int)item.week);
                dateList.Add("(" + weekhelp3.DateStart.ToString("MM.dd") + "-" + weekhelp3.DateEnd.ToString("MM.dd") + ") " + item.week);
            }
            result.weekListAndYear = dateList;
            return Json(result, JsonRequestBehavior.AllowGet);
        }


        /// <summary>
        ///  月度价格行情曲线
        /// </summary>
        /// <param name="yjxzqid">一级行政区id</param>
        /// <param name="ncpid">农产品id</param>
        /// <returns></returns>
        public JsonResult MonthPriceLineAJAXData(int yjxzqid, int ncpid, int yearStart, int monthStart, int yearEnd, int monthEnd)
        {
            V_yjmonthalljgDal dal = new V_yjmonthalljgDal();
            var result = new EchartsModel();


            //如果年月为空,默认显示近12个月
            if (string.IsNullOrEmpty(yearStart.ToString()) || string.IsNullOrEmpty(monthStart.ToString()) || string.IsNullOrEmpty(yearStart.ToString()) || string.IsNullOrEmpty(monthEnd.ToString()))
            {
             
                var now = DateTime.Now;
                DateTime start1 = new DateTime();
                start1 = now.AddMonths(-12);
                yearStart = start1.Year;
                monthStart = start1.Month;
                yearEnd = now.Year;
                monthEnd = now.Month;

            }

            var data2 = dal.SelectList( yjxzqid, ncpid,  yearStart,  monthStart,  yearEnd,  monthEnd);

            //记录表数据
            result.lsjgList = data2.OrderBy(d => d.cjyear).ThenBy(d => d.cjmonth).Select(d => d.lsjg).ToList();
            result.pfjgList = data2.OrderBy(d => d.cjyear).ThenBy(d => d.cjmonth).Select(d => d.pfjg).ToList();
            result.ttjgList = data2.OrderBy(d => d.cjyear).ThenBy(d => d.cjmonth).Select(d => d.ttjg).ToList();
            result.monthList = data2.OrderBy(d => d.cjyear).ThenBy(d => d.cjmonth).Select(d => d.cjmonth).ToList();
            result.jylList = data2.OrderBy(d => d.cjyear).ThenBy(d => d.cjmonth).Select(d => d.jyl).ToList();
            return Json(result, JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        ///  月度价格行情曲线
        /// </summary>
        /// <param name="yjxzqid">一级行政区id</param>
        /// <param name="ncpid">农产品id</param>
        /// <returns></returns>
        public JsonResult SZMonthPriceLineAJAXData(int yjxzqid, int ncpid, int yearStart, int monthStart, int yearEnd, int monthEnd)
        {
            var dal = new V_yjmonthzrsjjgDal();
            var result = new EchartsModel();
            //如果年月为空,默认显示近12个月
            if (string.IsNullOrEmpty(yearStart.ToString()) || string.IsNullOrEmpty(monthStart.ToString()) || string.IsNullOrEmpty(yearStart.ToString()) || string.IsNullOrEmpty(monthEnd.ToString()))
            {
                var now = DateTime.Now;
                DateTime start1 = new DateTime();
                start1 = now.AddMonths(-12);
                yearStart = start1.Year;
                monthStart = start1.Month;
                yearEnd = now.Year;
                monthEnd = now.Month;
            }

            var data2 = dal.SelectList(yjxzqid, ncpid, yearStart, monthStart, yearEnd, monthEnd);
            //记录表数据
            result.pfjgList = data2.OrderBy(d => d.cjyear).ThenBy(d => d.cjmonth).Select(d => d.pfjg).ToList();
            result.monthList = data2.OrderBy(d => d.cjyear).ThenBy(d => d.cjmonth).Select(d => d.cjmonth).ToList();
            return Json(result, JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// 同一地区不同品种价格柱状图
        /// </summary>
        /// <returns></returns>
        public JsonResult RegionProductsPriceBarAJAXData(int yjxzqid, int[] ncpid,DateTime date)
        {
            //测试用例
            //yjxzqid = 9;
            //ncpid = new int[] { 35, 36, 38 };
            var result = new EchartsModel();
            if (date == null)
            {
                  var now = DateTime.Now;
              //  var now = DateTime.Parse("2016-06-15");
                date = now.AddDays(-1); //近1天(昨天)
            } 
            var data = db.v_yjdatealljg .Where(d => ncpid.Contains(d.ncpid) && d.yjxzqid == yjxzqid && (d.cjrq == date)).ToList();
            result.lsjgList= data.OrderBy(d => d.cjrq).Select(d => d.lsjg).ToList();
            result.pfjgList = data.OrderBy(d => d.cjrq).Select(d => d.pfjg).ToList();
            result.ttjgList = data.OrderBy(d => d.cjrq).Select(d => d.ttjg).ToList();
            result.ncpmcList = data.OrderBy(d => d.cjrq).Select(d => d.ncpmc).ToList();
            result.jylList = data.OrderBy(d => d.cjrq).Select(d => d.jyl).ToList();
            return Json(result, JsonRequestBehavior.AllowGet);
        }
        
        /// <summary>
        /// 同一品种不同地区的价格柱状图
        /// </summary>
        /// <returns></returns>
        public JsonResult ProductRegionsPriceBarAJAXData(int[] yjxzqid, int ncpid, DateTime? date)
        {
            //测试用例
            //yjxzqid = 9;
            //   yjxzqid = new int[] { 9, 4, 8 };
            var result = new EchartsModel();
            if (date == null)
            {
                 var now = DateTime.Now;
               // var now = DateTime.Parse("2016-06-15");
                date = now.AddDays(-1); //近1天(昨天)
            }
            var data = db.v_yjdatealljg.Where(d => d.ncpid== ncpid && yjxzqid.Contains(d.yjxzqid) && (d.cjrq == date)).ToList();
            result.lsjgList = data.OrderBy(d => d.cjrq).Select(d => d.lsjg).ToList();
            result.pfjgList = data.OrderBy(d => d.cjrq).Select(d => d.pfjg).ToList();
            result.ttjgList = data.OrderBy(d => d.cjrq).Select(d => d.ttjg).ToList();
            result.yjxzqnameList = data.OrderBy(d => d.cjrq).Select(d => d.yjxzqname).ToList();
            result.jylList = data.OrderBy(d => d.cjrq).Select(d => d.jyl).ToList();
            return Json(result, JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// 同一品种不同地区的价格柱状图
        /// </summary>
        /// <returns></returns>
        public JsonResult SZProductRegionsPriceBarAJAXData(int[] yjxzqid, int ncpid, DateTime? date)
        {
            //测试用例
            //yjxzqid = 9;
            //   yjxzqid = new int[] { 9, 4, 8 };
            var result = new EchartsModel();
            if (date == null)
            {
                var now = DateTime.Now;
                // var now = DateTime.Parse("2016-06-15");
                date = now.AddDays(-1); //近1天(昨天)
            }
            var data = db.v_yjdatezrsjjg.Where(d => d.ncpid == ncpid && yjxzqid.Contains(d.yjxzqid) && (d.cjrq == date)).ToList();
    
            result.pfjgList = data.OrderBy(d => d.cjrq).Select(d => d.pfjg).ToList();
            result.yjxzqnameList = data.OrderBy(d => d.cjrq).Select(d => d.yjxzqname).ToList();     
            return Json(result, JsonRequestBehavior.AllowGet);
        }

    }
}

View Code

linq部分方法改写 类

Echarts 数据视图 生成Excel的方法 Echarts 数据视图 生成Excel的方法

  1 using System;
  2 using System.Collections.Generic;
  3 using System.Linq;
  4 using System.Linq.Expressions;
  5 using System.Reflection;
  6 using System.Web;
  7 using Vegetable.Models;
  8 
  9 namespace Vegetable.DAL
 10 {
 11     public static class QueryableExtension
 12     {
 13 
 14         public static IQueryable<T> OrderBy<T>(this IQueryable<T> source, string[] propertyName, bool[] ascending) where T : class
 15         {
 16             Type type = typeof(T);
 17 
 18             for (int i = 0; i < propertyName.Length; i++)
 19             {
 20 
 21                 PropertyInfo property = type.GetProperty(propertyName[i]);
 22                 if (property == null)
 23                     throw new ArgumentException("propertyName", "Not Exist");
 24 
 25                 ParameterExpression param = Expression.Parameter(type, "p");
 26                 Expression propertyAccessExpression = Expression.MakeMemberAccess(param, property);
 27                 LambdaExpression orderByExpression = Expression.Lambda(propertyAccessExpression, param);
 28 
 29                 string methodName = ascending[i] ? "OrderBy" : "OrderByDescending";
 30                 if (i != 0)
 31                 {
 32                     methodName = ascending[i] ? "ThenBy" : "ThenByDescending";
 33                 }
 34 
 35                 MethodCallExpression resultExp = Expression.Call(typeof(Queryable), methodName, new Type[] { type, property.PropertyType }, source.Expression, Expression.Quote(orderByExpression));
 36                 source = source.Provider.CreateQuery<T>(resultExp);
 37 
 38             }
 39 
 40 
 41             return source;
 42         }
 43 
 44 
 45         public static IQueryable<T> Where<T>(this IQueryable<T> source, FilterRule[] filterRules) where T : class
 46         {
 47             if (filterRules == null)
 48             {
 49                 return source;
 50             }
 51             Type type = typeof(T);
 52 
 53             ParameterExpression param = Expression.Parameter(type, "c");
 54 
 55             Expression<Func<T, bool>> op = null;
 56 
 57             foreach (var rule in filterRules)
 58             {
 59                 PropertyInfo property = type.GetProperty(rule.Field);
 60                 if (property == null)
 61                 {
 62                     continue;
 63                 }
 64                 //c.Field==Value
 65                 //c=>c.Field.Contains(Value)
 66                 Expression left = Expression.Property(param, property);
 67 
 68                 Expression right = Expression.Constant(rule.Value);
 69                 Type valueType = property.PropertyType;
 70                 if (rule.Value == null || rule.Value == "") continue;
 71                 DateTime inputDateTime = DateTime.Now;
 72                 try
 73                 {
 74 
 75                     if (valueType == typeof(int) || valueType == typeof(int?))
 76                     {
 77                         right = Expression.Constant(Convert.ToInt32(rule.Value.Split('.')[0]));
 78                     }
 79                     else if (valueType == typeof(short) || valueType == typeof(short?))
 80                     {
 81                         right = Expression.Constant(Convert.ToInt16(rule.Value.Split('.')[0]));
 82                     }
 83                     else if (valueType == typeof(byte) || valueType == typeof(byte?))
 84                     {
 85                         right = Expression.Constant(Convert.ToByte(rule.Value.Split('.')[0]));
 86                     }
 87                     else if (valueType == typeof(long) || valueType == typeof(long?))
 88                     {
 89                         right = Expression.Constant(Convert.ToInt64(rule.Value));
 90                     }
 91                     else if (valueType == typeof(float) || valueType == typeof(float?))
 92                     {
 93                         right = Expression.Constant(Convert.ToSingle(rule.Value));
 94                     }
 95                     else if (valueType == typeof(double) || valueType == typeof(double?))
 96                     {
 97                         right = Expression.Constant(Convert.ToDouble(rule.Value));
 98                     }
 99                     else if (valueType == typeof(decimal) || valueType == typeof(decimal?))
100                     {
101                         right = Expression.Constant(Convert.ToDecimal(rule.Value));
102                     }
103                     else if (valueType == typeof(DateTime) || valueType == typeof(DateTime?))
104                     {
105                         inputDateTime = Convert.ToDateTime(rule.Value);
106                         right = Expression.Constant(Convert.ToDateTime(rule.Value));
107                     }
108                     else if (valueType == typeof(Guid) || valueType == typeof(Guid?))
109                     {
110                         right = Expression.Constant(Guid.Parse(rule.Value));
111                     }
112 
113                 }
114                 catch (Exception ex)
115                 {
116                     Console.WriteLine(ex.Message);
117                     break;
118                 }
119 
120 
121                 Expression filter = Expression.Equal(left, right);
122                 Expression filter2 = null;
123                 MethodInfo method;
124 
125                 switch (rule.Op)
126                 {
127                     case OP.contains:
128                         //BinaryExpression
129                         if (valueType == typeof(string))
130                         {
131                             method = typeof(string).GetMethod("Contains", new[] { typeof(string) });
132                             filter = Expression.Call(left, method, right);
133                         }
134                         else if (valueType == typeof(DateTime) || valueType == typeof(DateTime?))
135                         {
136                             right = Expression.Constant(inputDateTime.Date);
137                             filter = Expression.GreaterThanOrEqual(left, right);
138                             right = Expression.Constant(inputDateTime.Date.AddDays(1));
139                             filter2 = Expression.LessThan(left, right);
140                         }
141                         else
142                         {
143                             filter = Expression.Equal(left, right);
144                         }
145                         break;
146                     case OP.equal:
147                         filter = Expression.Equal(left, right);
148                         break;
149                     case OP.notequal:
150                         filter = Expression.NotEqual(left, right);
151                         break;
152                     case OP.beginwith:
153                         method = typeof(string).GetMethod("StartsWith", new[] { typeof(string) });
154 
155                         filter = Expression.Call(left, method, right);
156                         break;
157                     case OP.endwith:
158                         method = typeof(string).GetMethod("EndsWith", new[] { typeof(string) });
159 
160                         filter = Expression.Call(left, method, right);
161                         break;
162                     case OP.less:
163                         filter = Expression.LessThan(left, right);
164                         break;
165                     case OP.lessorequal:
166                         filter = Expression.LessThanOrEqual(left, right);
167                         break;
168                     case OP.greater:
169                         filter = Expression.GreaterThan(left, right);
170                         break;
171                     case OP.greaterorequal:
172                         filter = Expression.GreaterThanOrEqual(left, right);
173                         break;
174                     default:
175                         break;
176                 }
177 
178 
179 
180                 var lambda = Expression.Lambda<Func<T, bool>>(filter, param);
181                 if (op == null)
182                 {
183                     op = lambda;
184                 }
185                 else
186                 {
187                     op = Expression.Lambda<Func<T, bool>>(Expression.And(op.Body, lambda.Body), op.Parameters);
188                 }
189 
190                 if (filter2 != null)
191                 {
192                     var lambda2 = Expression.Lambda<Func<T, bool>>(filter2, param);
193                     op = Expression.Lambda<Func<T, bool>>(Expression.And(op.Body, lambda2.Body), op.Parameters);
194                 }
195             }
196 
197             if (op != null)
198             {
199                 source = source.Where(op);
200             }
201             return source;
202         }
203 
204 
205         public static IQueryable<T> Where<T>(this IQueryable<T> source, Filter[] filters) where T : class
206         {
207             if (filters == null)
208             {
209                 return source;
210             }
211             Type type = typeof(T);
212 
213             ParameterExpression param = Expression.Parameter(type, "c");
214 
215             Expression<Func<T, bool>> op = null;
216 
217 
218             foreach (var rule in filters)
219             {
220                 PropertyInfo property = type.GetProperty(rule.Field);
221                 if (property == null)
222                 {
223                     continue;
224                 }
225                 //c.Field==Value
226                 //c=>(c.Field.Contains(Value) || c.Field.Contains(Value))
227                 Exception outExc = new Exception();
228 
229                 Expression left = Expression.Property(param, property);
230                 Type valueType = property.PropertyType;
231                 if (rule.Value == null || rule.Value.Length <= 0) continue;
232 
233                 Expression<Func<T, bool>> lambdaOut = null;
234                 foreach (var v in rule.Value)
235                 {
236                     Expression right = Expression.Constant(v);
237                     DateTime inputDateTime = DateTime.Now;
238                     try
239                     {
240 
241                         if (valueType == typeof(int) || valueType == typeof(int?))
242                         {
243                             right = Expression.Constant(Convert.ToInt32(v.Split('.')[0]));
244                         }
245                         else if (valueType == typeof(short) || valueType == typeof(short?))
246                         {
247                             right = Expression.Constant(Convert.ToInt16(v.Split('.')[0]));
248                         }
249                         else if (valueType == typeof(byte) || valueType == typeof(byte?))
250                         {
251                             right = Expression.Constant(Convert.ToByte(v.Split('.')[0]));
252                         }
253                         else if (valueType == typeof(long) || valueType == typeof(long?))
254                         {
255                             right = Expression.Constant(Convert.ToInt64(v));
256                         }
257                         else if (valueType == typeof(float) || valueType == typeof(float?))
258                         {
259                             right = Expression.Constant(Convert.ToSingle(v));
260                         }
261                         else if (valueType == typeof(double) || valueType == typeof(double?))
262                         {
263                             right = Expression.Constant(Convert.ToDouble(v));
264                         }
265                         else if (valueType == typeof(decimal) || valueType == typeof(decimal?))
266                         {
267                             right = Expression.Constant(Convert.ToDecimal(v));
268                         }
269                         else if (valueType == typeof(DateTime) || valueType == typeof(DateTime?))
270                         {
271                             inputDateTime = Convert.ToDateTime(v);
272                             right = Expression.Constant(Convert.ToDateTime(v));
273                         }
274                         else if (valueType == typeof(Guid) || valueType == typeof(Guid?))
275                         {
276                             right = Expression.Constant(Guid.Parse(v));
277                         }
278 
279                     }
280                     catch (Exception ex)
281                     {
282                         Console.WriteLine(ex.Message);
283                         break;
284                     }
285 
286 
287                     Expression filter = Expression.Equal(left, right);
288                     Expression filter2 = null;
289                     MethodInfo method;
290 
291                     switch (rule.Op)
292                     {
293                         case OP.contains:
294                             //BinaryExpression
295                             if (valueType == typeof(string))
296                             {
297                                 method = typeof(string).GetMethod("Contains", new[] { typeof(string) });
298                                 filter = Expression.Call(left, method, right);
299                             }
300                             else if (valueType == typeof(DateTime) || valueType == typeof(DateTime?))
301                             {
302                                 right = Expression.Constant(inputDateTime.Date);
303                                 filter = Expression.GreaterThanOrEqual(left, right);
304                                 right = Expression.Constant(inputDateTime.Date.AddDays(1));
305                                 filter2 = Expression.LessThan(left, right);
306                             }
307                             else
308                             {
309                                 filter = Expression.Equal(left, right);
310                             }
311                             break;
312                         case OP.equal:
313                             filter = Expression.Equal(left, right);
314                             break;
315                         case OP.notequal:
316                             filter = Expression.NotEqual(left, right);
317                             break;
318                         case OP.beginwith:
319                             method = typeof(string).GetMethod("StartsWith", new[] { typeof(string) });
320 
321                             filter = Expression.Call(left, method, right);
322                             break;
323                         case OP.endwith:
324                             method = typeof(string).GetMethod("EndsWith", new[] { typeof(string) });
325 
326                             filter = Expression.Call(left, method, right);
327                             break;
328                         case OP.less:
329                             filter = Expression.LessThan(left, right);
330                             break;
331                         case OP.lessorequal:
332                             filter = Expression.LessThanOrEqual(left, right);
333                             break;
334                         case OP.greater:
335                             filter = Expression.GreaterThan(left, right);
336                             break;
337                         case OP.greaterorequal:
338                             filter = Expression.GreaterThanOrEqual(left, right);
339                             break;
340                         default:
341                             break;
342                     }
343 
344 
345 
346                     var lambda = Expression.Lambda<Func<T, bool>>(filter, param);
347                     if (lambdaOut == null)
348                     {
349                         lambdaOut = lambda;
350                     }
351                     else
352                     {
353                         lambdaOut = Expression.Lambda<Func<T, bool>>(Expression.Or(lambdaOut.Body, lambda.Body), lambdaOut.Parameters);
354                     }
355 
356                     if (filter2 != null)
357                     {
358                         var lambda2 = Expression.Lambda<Func<T, bool>>(filter2, param);
359                         lambdaOut = Expression.Lambda<Func<T, bool>>(Expression.And(lambdaOut.Body, lambda2.Body), lambdaOut.Parameters);
360                     }
361                 }
362                 if (op == null)
363                 {
364                     op = lambdaOut;
365                 }
366                 else
367                 {
368                     op = Expression.Lambda<Func<T, bool>>(Expression.And(op.Body, lambdaOut.Body), op.Parameters);
369                 }
370 
371             }
372             if (op != null)
373             {
374                 source = source.Where(op);
375             }
376             return source;
377 
378         }
379 
380         public static IQueryable<T> Where<T>(this IQueryable<T> source, string[] columnNames, string filterString)
381         {
382 
383             Type type = typeof(T);
384 
385             ParameterExpression param = Expression.Parameter(type, "c");
386 
387             Expression right = Expression.Constant(filterString);
388 
389             //1!=1
390             //Expression op = Expression.NotEqual(Expression.Constant(1), Expression.Constant(1));
391             Expression<Func<T, bool>> op = null;
392 
393 
394             foreach (var column in columnNames)
395             {
396                 PropertyInfo property = type.GetProperty(column);
397                 if (property == null)
398                 {
399                     continue;
400                 }
401                 //c.Field==Value
402                 //c=>c.Field.Contains(Value)
403                 Expression left = Expression.Property(param, property);
404 
405                 Type valueType = property.PropertyType;
406                 if (valueType != typeof(string)) continue;
407                 if (filterString == null || filterString == "") continue;
408 
409 
410                 MethodInfo method = typeof(string).GetMethod("Contains", new[] { typeof(string) });
411 
412 
413                 Expression filter = Expression.Call(left, method, right);
414 
415                 var lambda = Expression.Lambda<Func<T, bool>>(filter, param);
416                 if (op == null)
417                 {
418                     op = lambda;
419                 }
420                 else
421                 {
422 
423                     op = Expression.Lambda<Func<T, bool>>(Expression.Or(op.Body, lambda.Body), op.Parameters);
424                 }
425             }
426 
427             if (op != null)
428             {
429 
430                 source = source.Where(op);
431             }
432             return source;
433         }
434     }
435 }

View Code

日期转年周类

Echarts 数据视图 生成Excel的方法 Echarts 数据视图 生成Excel的方法

  1 using System;
  2 using System.Collections.Generic;
  3 using System.Linq;
  4 using System.Web;
  5 
  6 namespace Vegetable.DBHelper
  7 {
  8     /// <summary>
  9     /// 星期一作为一周的开始,第一个完整的周作为第一周
 10     /// </summary>
 11     public class WeekHelper
 12     {
 13         /// <summary>
 14         /// 开始日期
 15         /// </summary>
 16         public DateTime DateStart { get; private set; }
 17         /// <summary>
 18         /// 结束日期
 19         /// </summary>
 20         public DateTime DateEnd { get; private set; }
 21 
 22         /// <summary>
 23         /// 年
 24         /// </summary>
 25         public int Year { get; private set; }
 26 
 27         /// <summary>
 28         /// 周
 29         /// </summary>
 30         public int Week { get; private set; }
 31 
 32         /// <summary>
 33         /// 一年开始的日期
 34         /// </summary>
 35         public DateTime YearStartDate { get; private set; }
 36 
 37 
 38         /// <summary>
 39         /// 一年最大周数
 40         /// </summary>
 41         public int MaxWeek { get; private set; }
 42 
 43         public override string ToString()
 44         {
 45             return string.Format("{0}年第{1}周", Year, Week);
 46         }
 47 
 48         private void SetYearStartDay(int year)
 49         {
 50             YearStartDate = new DateTime(year, 1, 1);
 51             var addDay = 8 - (int)YearStartDate.DayOfWeek;
 52             if (addDay >= 7)
 53             {
 54                 addDay = addDay - 7;
 55             }
 56             YearStartDate = YearStartDate.AddDays(addDay);
 57         }
 58 
 59         public WeekHelper(DateTime date)
 60         {
 61             SetYearStartDay(date.Year);
 62             if (date < YearStartDate)
 63             {
 64                 SetYearStartDay(date.Year - 1);
 65             }
 66             MaxWeek = ((new DateTime(YearStartDate.Year, 12, 31) - YearStartDate).Days / 7) + 1;
 67             Year = YearStartDate.Year;
 68             Week = ((date - YearStartDate).Days / 7) + 1;
 69             DateStart = YearStartDate.AddDays((Week - 1) * 7);
 70             DateEnd = YearStartDate.AddDays(Week * 7 - 1);
 71         }
 72 
 73 
 74 
 75         public WeekHelper(int year, int week)
 76         {
 77             SetYearStartDay(year);
 78             var date = YearStartDate.AddDays((week - 1) * 7);
 79             if (date < YearStartDate)
 80             {
 81                 SetYearStartDay(year - 1);
 82             }
 83 
 84             MaxWeek = ((new DateTime(YearStartDate.Year, 12, 31) - YearStartDate).Days / 7) + 1;
 85             while (week > MaxWeek)
 86             {
 87                 year = year + 1;
 88                 week = week - MaxWeek;
 89                 SetYearStartDay(year);
 90                 date = YearStartDate.AddDays((week - 1) * 7);
 91                 MaxWeek = ((new DateTime(YearStartDate.Year, 12, 31) - YearStartDate).Days / 7) + 1;
 92             }
 93 
 94             Year = YearStartDate.Year;
 95             Week = ((date - YearStartDate).Days / 7) + 1;
 96             DateStart = YearStartDate.AddDays((Week - 1) * 7);
 97             DateEnd = YearStartDate.AddDays(Week * 7 - 1);
 98         }
 99     }
100 }

View Code

sqlHelper类

Echarts 数据视图 生成Excel的方法 Echarts 数据视图 生成Excel的方法

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;

namespace Vegetable.DBHelper
{
    public static class SqlHelper
    {
        private static readonly string conStr = ConfigurationManager.ConnectionStrings["lyc2ConnString"].ConnectionString;

        //insert delete update
        public static int ExecuteNonQuery(string sql, params SqlParameter[] pms)
        {
            using (SqlConnection con = new SqlConnection(conStr))
            {
                using (SqlCommand cmd = new SqlCommand(sql, con))
                {
                    if (pms != null)
                    {
                        cmd.Parameters.AddRange(pms);
                    }
                    con.Open();
                    return cmd.ExecuteNonQuery();
                }
            }
        }

        //返回单个值
        public static object ExecuteScalar(string sql, params SqlParameter[] pms)
        {
            using (SqlConnection con = new SqlConnection(conStr))
            {
                using (SqlCommand cmd = new SqlCommand(sql, con))
                {
                    if (pms != null)
                    {
                        cmd.Parameters.AddRange(pms);
                    }
                    con.Open();
                    return cmd.ExecuteScalar();
                }
            }
        }

        //执行返回DataReader
        public static SqlDataReader ExecuteReader(string sql,  params SqlParameter[] pms)
        {
            SqlConnection con = new SqlConnection(conStr);
            using (SqlCommand cmd = new SqlCommand(sql, con))
            {
                if (pms != null)
                {
                    cmd.Parameters.AddRange(pms);
                }
                //con.Open();
                try
                {
                    if (con.State == ConnectionState.Closed)
                    {
                        con.Open();
                    }
                    return cmd.ExecuteReader(CommandBehavior.CloseConnection);
                }
                catch
                {
                    con.Close();
                    con.Dispose();
                    throw;
                }
            }
        }


        //查询多行 
        public static DataTable ExecuteDataTable(string sql, params SqlParameter[] pms)
        {
            DataTable dt = new DataTable();
            using (SqlDataAdapter adapter = new SqlDataAdapter(sql, conStr))
            {
                if (pms != null)
                {
                    adapter.SelectCommand.Parameters.AddRange(pms);
                }
                adapter.Fill(dt);
            }

            return dt;
        }

        /// <summary>
        /// 将DbNull转换成null
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static object FromDbNull(object obj)
        {
            if (obj == DBNull.Value)
            {
                return null;
            }
            else
            {
                return obj;
            }
        }

        /// <summary>
        /// 将null转换成DbNull
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static object ToDbNull(object obj)
        {
            if (obj == null)
            {
                return DBNull.Value;
            }
            else
            {
                return obj;
            }
        }


        /// <summary>
        ///  数组转字符串 逗号分隔
        /// </summary>
        /// <param name="ncpid"></param>
        /// <returns></returns>
        public static String ArrayToString(int[] ncpid)
        {
            string temp = "";
            for (int i = 0; i < ncpid.Length; i++)
            {
                if (i < ncpid.Length - 1)
                {
                    temp = temp + ncpid[i] + ",";
                }
                else
                {
                    temp = temp + ncpid[i];
                }

            }
            return temp;
        }
    }

}

View Code

参考过的文章:

https://blog.csdn.net/wwp231/article/details/51675023

http://www.cmsdx.com/wenzhang/329.html

点赞
收藏
评论区
推荐文章
blmius blmius
3年前
MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1
文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s
Easter79 Easter79
3年前
swap空间的增减方法
(1)增大swap空间去激活swap交换区:swapoff v /dev/vg00/lvswap扩展交换lv:lvextend L 10G /dev/vg00/lvswap重新生成swap交换区:mkswap /dev/vg00/lvswap激活新生成的交换区:swapon v /dev/vg00/lvswap
皕杰报表之UUID
​在我们用皕杰报表工具设计填报报表时,如何在新增行里自动增加id呢?能新增整数排序id吗?目前可以在新增行里自动增加id,但只能用uuid函数增加UUID编码,不能新增整数排序id。uuid函数说明:获取一个UUID,可以在填报表中用来创建数据ID语法:uuid()或uuid(sep)参数说明:sep布尔值,生成的uuid中是否包含分隔符'',缺省为
待兔 待兔
5个月前
手写Java HashMap源码
HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程22
Jacquelyn38 Jacquelyn38
3年前
2020年前端实用代码段,为你的工作保驾护航
有空的时候,自己总结了几个代码段,在开发中也经常使用,谢谢。1、使用解构获取json数据let jsonData  id: 1,status: "OK",data: 'a', 'b';let  id, status, data: number   jsonData;console.log(id, status, number )
Easter79 Easter79
3年前
Twitter的分布式自增ID算法snowflake (Java版)
概述分布式系统中,有一些需要使用全局唯一ID的场景,这种时候为了防止ID冲突可以使用36位的UUID,但是UUID有一些缺点,首先他相对比较长,另外UUID一般是无序的。有些时候我们希望能使用一种简单一些的ID,并且希望ID能够按照时间有序生成。而twitter的snowflake解决了这种需求,最初Twitter把存储系统从MySQL迁移
Wesley13 Wesley13
3年前
mysql设置时区
mysql设置时区mysql\_query("SETtime\_zone'8:00'")ordie('时区设置失败,请联系管理员!');中国在东8区所以加8方法二:selectcount(user\_id)asdevice,CONVERT\_TZ(FROM\_UNIXTIME(reg\_time),'08:00','0
Wesley13 Wesley13
3年前
00:Java简单了解
浅谈Java之概述Java是SUN(StanfordUniversityNetwork),斯坦福大学网络公司)1995年推出的一门高级编程语言。Java是一种面向Internet的编程语言。随着Java技术在web方面的不断成熟,已经成为Web应用程序的首选开发语言。Java是简单易学,完全面向对象,安全可靠,与平台无关的编程语言。
Wesley13 Wesley13
3年前
MySQL部分从库上面因为大量的临时表tmp_table造成慢查询
背景描述Time:20190124T00:08:14.70572408:00User@Host:@Id:Schema:sentrymetaLast_errno:0Killed:0Query_time:0.315758Lock_
Python进阶者 Python进阶者
11个月前
Excel中这日期老是出来00:00:00,怎么用Pandas把这个去除
大家好,我是皮皮。一、前言前几天在Python白银交流群【上海新年人】问了一个Pandas数据筛选的问题。问题如下:这日期老是出来00:00:00,怎么把这个去除。二、实现过程后来【论草莓如何成为冻干莓】给了一个思路和代码如下:pd.toexcel之前把这