EasyUI-datagrid插件,動態加載數據分頁Ajax數據下載

由於最近做一個項目的數據查詢,很多都需要查,但一個一個寫又麻煩,百度了下發現我們用的EasyUI框架挺厲害的,就百度了下DataGrid的用法,此處涉及到了數據的動態加載,分頁,以及永Ajax方法下載數據,但不是直接下載,是把數據先用Excel存起來,然後去下載,只是下載前我把之前生成的Excel刪掉了.此處我用Ajax去獲取數據,超過六七千的json數據傳遞不到前臺.

http://www.jeasyui.net/demo/340.html

這是完整的前臺代碼


<head id="Head1">
    <title>StencilControl</title>
    <script src="/Scripts/jquery.min.js" type="text/javascript"></script>
    <script src="/Scripts/jquery.easyui.min.js" type="text/javascript"></script>
    @*<script src="/Scripts/locale/easyui-lang-zh_TW.js" type="text/javascript"></script>*@
    <link href="/Scripts/themes/icon.css" rel="stylesheet" type="text/css" />
    <link href="../../Scripts/themes/default/easyui.css" rel="stylesheet" type="text/css" />
    <script language="javascript" type="text/javascript">
        var strfunction = "";
        var strfunction1 = "";
        var plant = "";
        var po = "";
        var messageid = "";
        var startTime = "";
        var endTime = "";
        var json = "";
        var ColumnsList = "";
        var datagrid = "";

        function GetCondition() {
            plant = $("#SelDplant").find("option:selected").text();
            po = $("#iptpo").val().toUpperCase().replace(/^\s+|\s+$/g, "");
            messageid = $("#iptMesssageId").val().toUpperCase().replace(/^\s+|\s+$/g, "");
            startTime = $('#iptstarttime').datetimebox('getValue');
            endTime = $('#iptendtime').datetimebox('getValue');
        }
        $(function () {
            initMenu();
        });

        function initMenu() {
            $('#abtnMain').click(function () {
                strfunction1 = "QueryPoNew";
                strfunction = "QueryPoHeadNew";
                GetData(strfunction);
            });
            $('#abtnDownLoad').click(function () {
                QueryDownLoad();
            });
        }
        //獲取數據-----------------------------------------------
        function GetData(strfunction) {
            GetCondition();
            $.ajax({
                type: "POST",
                //url: "/PO_Management/QueryPoNew",
                url: "/PO_Management/" + strfunction1,
                datatype: "json",
                data: {
                    strQueryType: strfunction,
                    plant: plant,
                    po: po,
                    messageid: messageid,
                    startTime: startTime,
                    endTime: endTime
                },
                success: function (msg) {
                    var columnsAll = [];
                    if (msg.IsSuccess) {
                        json = eval("(" + msg.Message + ")");
                        ColumnsList = eval(json.Columns);
                        for (var i = 0; i < ColumnsList.length; i++) {
                            var col = {};
                            col['title'] = ColumnsList[i].COLUMN;
                            col['field'] = ColumnsList[i].COLUMN;
                            col['editor'] = false;
                            //col['width'] = 100;
                            col['align'] = 'center';
                            columnsAll.push(col);
                        }
                        LoadData(columnsAll);
                    }
                    else {
                        status = "FAIL";
                        $.messager.alert('Error', msg.Message, 'error');
                    }
                }
            });
        }
        //加載欄位和數據-----------------------------------------------
        function LoadData(columnsAll) {
            $("#showData").datagrid({
                //height: 500,
                loadMsg: 'Please hold on...',
                columns: [columnsAll]
            });
            datagrid = eval(json.Data);
            $('#showData').datagrid('loadData', datagrid);
        }
        //數據分頁------------------------------------------------------
        function pagerFilter(data) {
            if (typeof data.length == 'number' && typeof data.splice == 'function') {
                data = {
                    total: data.length,
                    rows: data
                }
            }
            var dg = $(this);
            var opts = dg.datagrid('options');
            var pager = dg.datagrid('getPager');
            pager.pagination({
                onSelectPage: function (pageNum, pageSize) {
                    opts.pageNumber = pageNum;
                    opts.pageSize = pageSize;
                    pager.pagination('refresh', {
                        pageNumber: pageNum,
                        pageSize: pageSize
                    });
                    dg.datagrid('loadData', data);
                }
            });
            if (!data.originalRows) {
                data.originalRows = (data.rows);
            }
            var start = (opts.pageNumber - 1) * parseInt(opts.pageSize);
            var end = start + parseInt(opts.pageSize);
            data.rows = (data.originalRows.slice(start, end));
            return data;
        }

        //數據下載--------------------------------------------------------
        function QueryDownLoad() {
            $.ajax({
                type: "POST",
                url: "/PO_Management/PAFGetCSVReport1",
                data: {
                    pafquery: JSON.stringify(datagrid),
                    Columns: JSON.stringify(ColumnsList)
                },
                // dataType类型:String 预期服务器返回的数据类型。
                datatype: "json",
                success: function (msg) {
                    if (msg.IsSuccess) {
                        window.location.href = "DownLoadExcel1?strResult=" + msg.Message;
                    }
                    else {
                        $.messager.alert('Error', msg.Message, 'error');
                    }
                }
            });
            //window.location.href = "DownLoadDataNew?strfunction=" + strfunction1 + "&plant=" + plant + "&po=" + po + "&messageid=" + messageid;
            //window.location.href = "PAFGetCSVReport?pafquery=" + JSON.stringify(datagrid) + "&Columns=" + JSON.stringify(ColumnsList);
        }
    </script>
</head>
<body>
    <div id="divmain">
        <div id="p" class="easyui-panel" title="OrderInquery" style="overflow: hidden; width: auto;
            min-width: 900px; height: auto; padding: 3px; background: #fafafa;">
            <!--查詢區-->
            <div>
                <table>
                    <tr>
                        <td style="text-align: right; width: 60px;">
                            Plant:
                        </td>
                        <td id="tdtime" style="text-align: right; width: 100px">
                            <select id="SelDplant" style="width: 120px; text-align: left;">
                                <option></option>
                            </select>
                        </td>
                        <td style="text-align: right; width: 60px">
                            Po:
                        </td>
                        <td style="text-align: right;">
                            <input id="iptpo" style="text-align: left; width: 100px" />
                        </td>
                        <td style="text-align: right; width: 80px">
                            Message ID:
                        </td>
                        <td style="text-align: right;">
                            <input id="iptMesssageId" style="text-align: left; width: 100px" />
                        </td>
                        <td style="text-align: right; width: 80px">
                            Start Time:
                        </td>
                        <td>
                            <input id="iptstarttime" class="easyui-datebox" data-options="required:true,showSeconds:false"
                                   style="width: 105px" />
                        </td>
                        <td style="text-align: right; width: 60px">
                            End Time:
                        </td>
                        <td>
                            <input id="iptendtime" class="easyui-datebox" data-options="required:true,showSeconds:false"
                                   style="width: 105px" />
                        </td>
                    </tr>
                </table>
            </div>
            <!--菜單按鈕區-->
            <div style="font-size: larger; padding: 3px; background: #fff; border: 1px solid #ccc;">
                <a href="javascript:void(0)" id="abtnMain" class="easyui-linkbutton" plain="true" iconcls="icon-search"> <span id="btnMain">PoMain</span></a>               
                <a href="javascript:void(0)" id="abtnDownLoad" class="easyui-linkbutton" plain="true" iconcls="icon-add"><span id="btnDownLoad">DownLoad</span></a>

            </div>
            <!--數據展示區-->
            <table class="easyui-datagrid" id="showData" style="width: auto;
            height: 500px" data-options="singleSelect: true,iconCls: 'icon-edit',fitColumns:true,rownumbers:true,pagination:true,
            pageSize: 20, rownumbers:true,loadFilter: pagerFilter, toolbar: '#toolbar'"></table>
        </div>
    </div>   
</body>

這是後臺獲取數據的代碼

 public ActionResult QueryPoNew(string strQueryType, string plant, string po, string messageid, string startTime, string endTime)
        {
            DataTable dtTemp = new DataTable();
            string strResult = string.Empty;
            Lib.PO_Management.Order_Inquiry orderInquery = new Order_Inquiry();
            try
            {
                if (strQueryType == "QueryPoHeadNew")
                {
                    dtTemp = orderInquery.QueryPoHead(plant, po, messageid, startTime, endTime);
                }
            }
            catch (Exception ex)
            {
                return Json(new { IsSuccess = false, Message = ex.Message });
            }
            if (dtTemp.Rows.Count > 0)
            {
                strResult = DataTableToJSON.DataTableToJsonColumnsRows("Data", dtTemp);
                return Json(new { IsSuccess = true, Message = strResult });
            }
            else
            {
                strResult = "NO DATA! ";
                return Json(new { IsSuccess = false, Message = strResult });
            }
        }

這是數據轉JSON的代碼     

        /// <summary>
        ///  
        /// </summary>
        /// <param name="jsonName"></param>
        /// <param name="dt"></param>
        /// <returns>{"Columns":[{"COLUMN":"A"},{"COLUMN":"B"}...{"COLUMN":"N"}],"Data":[{"A":"1","B":"2"..."N":"Num"},{"A":"11","B":"22"..."N":"Num1"}]}</returns>      

  public static string DataTableToJsonColumnsRows(string jsonName, DataTable dt)
        {
            StringBuilder Json = new StringBuilder();
            var name = "Columns";
            var Name1 = "COLUMN";
            Boolean flag = true;
            if (dt.Rows.Count > 0)
            {
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    Json.Append("{");
                    if (flag)
                    {
                        Json.Append("\"" + name + "\":[");
                        for (int k = 0; k < dt.Columns.Count; k++)
                        {
                            Json.Append("{\"" + Name1 + "\":\"" + dt.Columns[k].ColumnName.ToString().Trim() + "\"}");
                            if (k < dt.Columns.Count - 1)
                            {
                                Json.Append(",");
                            }
                        }
                        Json.Append("]," + jsonName + ":[{");
                    }
                    for (int j = 0; j < dt.Columns.Count; j++)
                    {
                        Json.Append("\"" + dt.Columns[j].ColumnName.ToString().Trim() + "\":\"" + dt.Rows[i][j].ToString().Trim() + "\"");
                        if (j < dt.Columns.Count - 1)
                        {
                            Json.Append(",");
                        }
                        flag = false;
                    }
                    Json.Append("}");
                    if (i < dt.Rows.Count - 1)
                    {
                        Json.Append(",");
                    }
                }
            }
            Json.Append("]}");
            return Json.ToString();
        }

這是數據下載的方法

  public ActionResult PAFGetCSVReport1(string pafquery, string Columns)
            {
                string strResult = string.Empty;
                string filename = "";
                filename = DateTime.Now.ToString("yyyyMMddhhmmss");
                if (pafquery.Length == 0 && Columns.Length == 0)
                {
                    return Json(new { IsSuccess = false, Message = "NO DATA" });
                }
                strResult = Lib.DBHelper.ExcelHelper.TableToExcelForCsv(pafquery, Columns, filename);
                if (strResult.Substring(0, 2) != "OK")
                {
                    return Json(new { IsSuccess = false, Message = "Export Fail" });
                }
                return Json(new { IsSuccess = true, Message = strResult });
            }
            public void DownLoadExcel(string strResult)
            {
                string strFilePath = "", strFileName = "";
                strFilePath = strResult.Substring(3);
                strFileName = strFilePath.Substring(strFilePath.LastIndexOf(@"\") + 1);

                System.Web.HttpContext.Current.Response.Clear();
                System.Web.HttpContext.Current.Response.Charset = "UTF-8";
                System.Web.HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.UTF8;
                System.Web.HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(strFileName, System.Text.Encoding.UTF8).ToString());            
                System.Web.HttpContext.Current.Response.ContentType = "application/ms-excel";
                System.Web.HttpContext.Current.Response.WriteFile(strResult.Substring(3));
                System.Web.HttpContext.Current.Response.Flush();
                System.Web.HttpContext.Current.Response.End();
                if (System.IO.File.Exists(strFilePath))
                {
                    System.IO.File.Delete(strFilePath);
                }            
            }

    這是數據存EXCEL的代碼 

//這裡用了Newtonsoft插件,可自行百度下載

https://www.newtonsoft.com/json

using System.IO;
using Newtonsoft.Json;
using NPOI.SS.UserModel;
using NPOI.HSSF.UserModel;
using NPOI.XSSF.UserModel;
using NPOI.OpenXml4Net;

         /// <summary>  
        /// 将数据导出到Excel文件中(Csv)  
        /// </summary>  
        /// <param name="dt"></param>  
        /// <param name="file"></param>  
        public static string TableToExcelForCsv(string pafquery, string Columns, string file)
        {
            Newtonsoft.Json.Linq.JArray jobjcol = (Newtonsoft.Json.Linq.JArray)JsonConvert.DeserializeObject(Columns);
            Newtonsoft.Json.Linq.JArray jobj = (Newtonsoft.Json.Linq.JArray)JsonConvert.DeserializeObject(pafquery);

            HSSFWorkbook hssfworkbook = new HSSFWorkbook();
            ISheet sheet = hssfworkbook.CreateSheet(file);
            string[] col = new string[100];
            //表头  
            IRow row = sheet.CreateRow(0);
            for (int i = 0; i < jobjcol.Count(); i++)
            {
                ICell cell = row.CreateCell(i);
                cell.SetCellValue(jobjcol[i]["COLUMN"].ToString());
                col[i] = jobjcol[i]["COLUMN"].ToString();
            }
            //数据  
            for (int i = 0; i < jobj.Count(); i++)
            {
                IRow row1 = sheet.CreateRow(i + 1);
                for (int j = 0; j < jobjcol.Count(); j++)
                {
                    ICell cell = row1.CreateCell(j);
                    cell.SetCellValue((jobj[i][col[j]].ToString()));
                }
            }
            var filePath = Path.Combine(System.Web.HttpContext.Current.Server.MapPath("~/TempFiles/DownLoad/"));
            string strFileName = System.Web.HttpContext.Current.Server.MapPath(@"\TempFiles\DownLoad\" + file + ".csv");
            //路徑是否存在,不存在則創建
            if (!Directory.Exists(filePath))
            {
                Directory.CreateDirectory(filePath);
            }
            //转为字节数组  
            MemoryStream stream = new MemoryStream();
            hssfworkbook.Write(stream);
            var buf = stream.ToArray();
            //保存为Excel文件  
            using (FileStream fs = new FileStream(strFileName, FileMode.Create, FileAccess.Write))
            {
                fs.Write(buf, 0, buf.Length);
                fs.Flush();
            }
            return "OK," + strFileName;
        }

這樣基本是可以查出數據并分頁的,我是自己實踐出來的,很多東西我只是會用,但是並不知道爲什麽.且使用中我遇到以下問題:
 a.我用的是Ajax想後臺請求數據,當數據達到六七千的時候,前臺無反應,後臺有數據

有優化方法的小夥伴,可以留言告訴我,大家一起交流進步,謝謝!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值