datagrid動態載入資料分頁下載EasyUI外掛
這是完整的前臺程式碼
<!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,但是不會有那種提示下載儲存的東西,毫無反應,但資料確實下載了
有優化方法的小夥伴,可以留言告訴我,大家一起交流進步,謝謝!