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

 <div id="scroll" style="width:500px;white-space:nowrap;overflow:hidden" >
        <span>
     <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" />

        </span>
    </div>

這是完整的前臺代碼

<!DOCTYPE html>
<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 = "QueryPoHead";
                strfunction = "QueryPoHeadNew";
                GetData(strfunction);
            });
            $('#abtnDownLoad').click(function () {
                QueryDownLoad();
            });
        }
        //獲取數據-----------------------------------------------
        function GetData(strfunction) {
            GetCondition();
            $.ajax({
                type: "POST",
                url: "/PO_Management/QueryPoNew",
                //url: "/PO_Management/" + strfunction,
                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...',
                //url: '',
                //fit: true,
                //method: 'get',
                //pagination: 'true',
                //pageSize: '20',
                //pageList: [5, 10, 20, 30, 50],
                //rownumbers: 'true',
                //border: 'false',
                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/PAFGetCSVReport",
                data: {
                    pafquery: JSON.stringify(datagrid),
                    Columns: JSON.stringify(ColumnsList)
                },
                // dataType类型:String 预期服务器返回的数据类型。
                datatype: "json"
                //success: function (msg) {
                //    if (msg.IsSuccess) {
                //        $.messager.alert('Succeed', '文件下載' + msg.Message, 'Succeed');
                //    }
                //    else {
                //        $.messager.alert('Error', msg.Message, 'error');
                //    }
                //}
            }); 
        }
    </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-add"> <span id="btnMain">Main</span></a>
                <a href="javascript:void(0)" id="abtnLine" class="easyui-linkbutton" plain="true" iconcls="icon-add"><span id="btnLine">Line</span></a>
                <a href="javascript:void(0)" id="abtnItem" class="easyui-linkbutton" plain="true" iconcls="icon-add"><span id="btnItem">Item</span></a>
                <a href="javascript:void(0)" id="abtnAll" class="easyui-linkbutton" plain="true" iconcls="icon-add"><span id="btnAll">All</span></a>
                <a href="javascript:void(0)" id="abtnAsbuild" class="easyui-linkbutton" plain="true" iconcls="icon-add"><span id="btnAsbuild">Asbuild</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>
</html>

這是後臺獲取數據的代碼

 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);
                }
                else if (strQueryType == "QueryPoLineNew")
                {
                    dtTemp = orderInquery.QueryPoLine(plant, po, messageid, startTime, endTime);
                }
                else if (strQueryType == "QueryPoItemNew")
                {
                    dtTemp = orderInquery.QueryPoItem(plant, po, messageid, startTime, endTime);
                }
                else if (strQueryType == "QueryPoAllNew")
                {
                    dtTemp = orderInquery.QueryPoAll(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();
        }


這是數據下載的方法

       [Description("PAFGetCSVReport")]
        public ActionResult PAFGetCSVReport(string pafquery, string Columns)
        {
            string strResult = string.Empty;
            string filename = "";
            filename = "test" + DateTime.Now.ToString("yyyyMMddhhmmss");
            if (pafquery.Length == 0 && Columns.Length == 0)
            {
                return Json(new { IsSuccess = false, Message = "系統錯誤" });
            }
            strResult = Lib.DBHelper.ExcelHelper.TableToExcelForCsv(pafquery, Columns, filename);
            if (strResult.Substring(0, 2) != "OK")
            {
                return Json(new { IsSuccess = false, Message = strResult });
            }
            return Json(new { IsSuccess = true, Message = strResult });
        }

這是數據存EXCEL的代碼

原來是傳入DataTable,我改成我傳入的數據了

這是EXCEL的

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插件,可自行百度下載<a href="https://www.newtonsoft.com/json"></a>
            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;
        }

這樣基本是可以查出數據并分頁的,我是自己實踐出來的,很多東西我只是會用,但是並不知道爲什麽.且使用中我遇到以下問題:
1.我用的是Ajax想後臺請求數據,當數據達到六七千的時候,前臺無反應,後臺有數據
2.文件下載,會保存數據,也生成了Excel,但是不會有那種提示下載保存的東西,毫無反應,但數據確實下載了

2已經解決,我先把數據導入EXCEL存起來,然後去下載

JS 

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');
                    }
                }
            });
        }

C#

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 DownLoadExcel1(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);
            }
        }

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

猜你喜欢

转载自blog.csdn.net/qq_41128526/article/details/83036134
今日推荐