jqGrid整合篇
jqgrid在隐藏状态下实例化导致看不到,需要重置大小;
$("#datagrid_" + ($(this).parent().index() == 0 ? "JD" : "ND")).setGridWidth(document.body.clientWidth); //界面大小变化时重置大小 $(window).resize(function () { $("#datagrid_JD").setGridWidth(document.body.clientWidth); $("#datagrid_ND").setGridWidth(document.body.clientWidth); });
jqgrid实现多级表头
//使用setGroupHeaders参数: $( "#datagrid" ).jqGrid( 'setGroupHeaders' , { useColSpanStyle : true , // 没有表头的列是否与表头列位置的空单元格合并 groupHeaders :[{ startColumnName :"timeId", //开始列 numberOfColumns : 18, //合并几列 titleText : "一级表头",//合并后父列名 }] }); $( "#datagrid" ).jqGrid( 'setGroupHeaders' , { useColSpanStyle : true , // 没有表头的列是否与表头列位置的空单元格合并 groupHeaders :[{ startColumnName :"http_dl_speed", //开始列 numberOfColumns : 6, //合并几列 titleText : "二级表头1,//合并后父列名 }, { startColumnName : "numofattachsucc_rate", //开始列 numberOfColumns : 3, //合并几列 titleText :"二级表头2" //合并后父列名 }] }); //注意:按照表头的级别顺序去初始化表头
table转jqGrid—只支持单行表头
//table转jqGrid—只支持单行表头 function tableToGrid(selector, options) { jQuery(selector).each(function() { if(this.grid) {return;} //Adedd from Tony Tomov // This is a small "hack" to make the width of the jqGrid 100% jQuery(this).width("99%"); var w = jQuery(this).width(); // Text whether we have single or multi select var inputCheckbox = jQuery('tr td:first-child input[type=checkbox]:first', jQuery(this)); var inputRadio = jQuery('tr td:first-child input[type=radio]:first', jQuery(this)); var selectMultiple = inputCheckbox.length > 0; var selectSingle = !selectMultiple && inputRadio.length > 0; var selectable = selectMultiple || selectSingle; //var inputName = inputCheckbox.attr("name") || inputRadio.attr("name"); // Build up the columnModel and the data var colModel = []; var colNames = []; jQuery('th', jQuery(this)).each(function() { if (colModel.length === 0 && selectable) { colModel.push({ name: '__selection__', index: '__selection__', width: 0, hidden: true }); colNames.push('__selection__'); } else { colModel.push({ name: jQuery(this).attr("id") || jQuery.trim(jQuery.jgrid.stripHtml(jQuery(this).html())).split(' ').join('_'), index: jQuery(this).attr("id") || jQuery.trim(jQuery.jgrid.stripHtml(jQuery(this).html())).split(' ').join('_'), width: jQuery(this).width() || 150 }); colNames.push(jQuery(this).html()); } }); var data = []; var rowIds = []; var rowChecked = []; jQuery('tbody > tr', jQuery(this)).each(function() { var row = {}; var rowPos = 0; jQuery('td', jQuery(this)).each(function() { if (rowPos === 0 && selectable) { var input = jQuery('input', jQuery(this)); var rowId = input.attr("value"); rowIds.push(rowId || data.length); if (input.is(":checked")) { rowChecked.push(rowId); } row[colModel[rowPos].name] = input.attr("value"); } else { row[colModel[rowPos].name] = jQuery(this).html(); } rowPos++; }); if(rowPos >0) { data.push(row); } }); // Clear the original HTML table jQuery(this).empty(); // Mark it as jqGrid jQuery(this).addClass("scroll"); jQuery(this).jqGrid(jQuery.extend({ datatype: "local", width: w, colNames: colNames, colModel: colModel, multiselect: selectMultiple //inputName: inputName, //inputValueCol: imputName != null ? "__selection__" : null }, options || {})); // Add data var a; for (a = 0; a < data.length; a++) { var id = null; if (rowIds.length > 0) { id = rowIds[a]; if (id && id.replace) { // We have to do this since the value of a checkbox // or radio button can be anything id = encodeURIComponent(id).replace(/[.\-%]/g, "_"); } } if (id === null) { id = a + 1; } jQuery(this).jqGrid("addRowData",id, data[a]); } // Set the selection for (a = 0; a < rowChecked.length; a++) { jQuery(this).jqGrid("setSelection",rowChecked[a]); } }); };
使用方式
tableToGrid("#table1"); tableToGrid("#table2"); $("#table1").jqGrid('gridDnD', {connectWith: "#table2"}); $("#table2").jqGrid('gridDnD', {connectWith: "#table1"});
//单元格格式化内容 formatter = function (cellvalue, options, rowdata) { return cellvalue+''; } //单元格属性设置 cellattr = function (rowId, tv, rawObject, cm, rdata) { return 'style="color:red"'; }
JqGrid合并列的单元格方法
//合并列的单元格方法 //gridComplete 事件 gridName 表ID,cellName 需合并列 function Merger(gridName, CellName) { var $gridName = $("#" + gridName + ""); //得到显示到界面的id集合 var mya = $gridName.getDataIDs(); //数据总行数 var length = mya.length; //定义合并行数 var rowSpanTaxCount = 1; for (var i = 0; i < length; i += rowSpanTaxCount) { //从当前行开始比对下面的信息 var before = $gridName.jqGrid('getRowData', mya[i]); rowSpanTaxCount = 1; for (j = i + 1; j <= length; j++) { //和上边的信息对比 如果值一样就合并行数+1 然后设置rowspan 让当前单元格隐藏 var end = $gridName.jqGrid('getRowData', mya[j]); if (before[CellName] == end[CellName]) { rowSpanTaxCount++; $gridName.setCell(mya[j], CellName, '', { display: 'none' }); } else { break; } } $gridName.setCell(mya[i], CellName, '', '', { rowspan: rowSpanTaxCount }); } }
//合并列的单元格方法(根据某些列合并) //gridName 表ID,cellName 需合并列,tCellNames 需根据某行合并 ['AreaName'] function jqGridMerger(gridName, cellName, tCellNames) { if (!tCellNames) { tCellNames = []; } else if (!(tCellNames instanceof Array)) { tCellNames = tCellNames.split(','); } tCellNames.push(cellName); var $gridName = $("#" + gridName + ""); //tCellNames = tCellNames.concat([cellName]); //得到显示到界面的id集合 var mya = $gridName.getDataIDs(); //当前显示多少条 var length = mya.length; //定义合并行数 var rowSpanTaxCount = 1; for (var i = 0; i < length; i += rowSpanTaxCount) { //从上到下获取一条信息 var before = $gridName.jqGrid('getRowData', mya[i]); //定义合并行数 rowSpanTaxCount = 1; for (j = i + 1; j <= length; j++) { //和上边的信息对比 如果值一样就合并行数+1 然后设置rowspan 让当前单元格隐藏(未固定表列) var end = $gridName.jqGrid('getRowData', mya[j]); if (MergerCondition(before, end, tCellNames)) {//before[tCellName] == end[tCellName] rowSpanTaxCount++; //$gridName.setCell(mya[j], cellName, '', { display: 'none' }); $("#" + cellName + mya[j], $gridName).hide(); } else { break; } //$gridName.setCell(mya[i], cellName, '', '', { rowspan: rowSpanTaxCount }); $("#" + cellName + mya[i], $gridName).attr("rowspan", rowSpanTaxCount); } } } //合并列的单元格 - 根据行条件判断 function MergerCondition(before, end, tCellNames) { for (var i = 0; i < tCellNames.length; i++) { if (before[tCellNames[i]] != end[tCellNames[i]]) { return false; } } return true; }
合并列的单元格方法需结合设置ID使用,使用方法如下:
$(document).ready(function() { var mydata = [ { id: "1", invdate: "2007-10-01", name: "test_test_test_test_test", note: "note", amount: "200.00", tax: "10.00", closed: true, ship_via: "TN", total: "210.00" }, { id: "2", invdate: "2007-10-02", name: "test2222222222222222", note: "note2", amount: "300.00", tax: "20.00", closed: false, ship_via: "FE", total: "320.00" }, { id: "3", invdate: "2007-09-01", name: "test3", note: "note3", amount: "400.00", tax: "30.00", closed: false, ship_via: "FE", total: "430.00" }, { id: "4", invdate: "2007-10-04", name: "test4444444444444444", note: "note4", amount: "200.00", tax: "10.00", closed: true, ship_via: "TN", total: "210.00" }, { id: "5", invdate: "2007-10-31", name: "test5", note: "note5", amount: "300.00", tax: "20.00", closed: false, ship_via: "FE", total: "320.00" }, { id: "6", invdate: "2007-09-06", name: "test6", note: "note6", amount: "400.00", tax: "30.00", closed: false, ship_via: "FE", total: "430.00" }, { id: "7", invdate: "2007-10-04", name: "test7", note: "note7", amount: "300.00", tax: "10.00", closed: true, ship_via: "TN", total: "210.00" }, { id: "8", invdate: "2007-10-03", name: "test8", note: "note8", amount: "300.00", tax: "20.00", closed: false, ship_via: "FE", total: "320.00" }, { id: "9", invdate: "2007-09-01", name: "test9", note: "note9", amount: "400.00", tax: "30.00", closed: false, ship_via: "TN", total: "430.00" }, { id: "10", invdate: "2007-09-08", name: "test10", note: "note10", amount: "500.00", tax: "30.00", closed: true, ship_via: "TN", total: "530.00" }, { id: "11", invdate: "2007-09-08", name: "test11", note: "note11", amount: "500.00", tax: "30.00", closed: false, ship_via: "FE", total: "530.00" }, { id: "12", invdate: "2007-09-10", name: "test12", note: "note12", amount: "300.00", tax: "30.00", closed: false, ship_via: "FE", total: "530.00" }, { id: "13", invdate: "2007-10-01", name: "test_test_test_test_test", note: "note", amount: "200.00", tax: "10.00", closed: true, ship_via: "TN", total: "210.00" }, { id: "14", invdate: "2007-10-02", name: "test2222222222222222", note: "note2", amount: "300.00", tax: "20.00", closed: false, ship_via: "FE", total: "320.00" }, { id: "15", invdate: "2007-09-01", name: "test3", note: "note3", amount: "400.00", tax: "30.00", closed: false, ship_via: "FE", total: "430.00" }, { id: "16", invdate: "2007-10-04", name: "test4444444444444444", note: "note4", amount: "200.00", tax: "10.00", closed: true, ship_via: "TN", total: "210.00" }, { id: "17", invdate: "2007-10-31", name: "test5", note: "note5", amount: "300.00", tax: "20.00", closed: false, ship_via: "FE", total: "320.00" }, { id: "18", invdate: "2007-09-06", name: "test6", note: "note6", amount: "500.00", tax: "30.00", closed: false, ship_via: "FE", total: "430.00" }, { id: "19", invdate: "2007-10-04", name: "test7", note: "note7", amount: "200.00", tax: "10.00", closed: true, ship_via: "TN", total: "210.00" }, { id: "20", invdate: "2007-10-03", name: "test8", note: "note8", amount: "300.00", tax: "20.00", closed: false, ship_via: "FE", total: "320.00" }, { id: "21", invdate: "2007-09-01", name: "test9", note: "note9", amount: "400.00", tax: "30.00", closed: false, ship_via: "TN", total: "430.00" }, { id: "22", invdate: "2007-09-08", name: "test10", note: "note10", amount: "500.00", tax: "30.00", closed: true, ship_via: "TN", total: "530.00" }, { id: "23", invdate: "2007-09-08", name: "test11", note: "note11", amount: "500.00", tax: "30.00", closed: false, ship_via: "FE", total: "530.00" }, { id: "24", invdate: "2007-09-10", name: "test12", note: "note12", amount: "500.00", tax: "30.00", closed: false, ship_via: "FE", total: "530.00" } ], grid = $("#list"); grid.jqGrid({ datatype: 'local', data: mydata, colNames: ['Inv No', 'Date', 'Client A', 'Client B', 'Amount', 'Tax', 'Total', 'Closed', 'Shipped via', 'Notes'], colModel: [ { name: 'id', index: 'id', width: 70, align: 'center', sorttype: 'int' }, { name: 'invdate', index: 'invdate', width: 80, align: 'center', sorttype: 'date', formatter: 'date', formatoptions: { newformat: 'd-M-Y' }, datefmt: 'd-M-Y' }, { name: 'name', index: 'name', width: 70, cellattr: function(rowId, tv, rawObject, cm, rdata) { //合并单元格 return 'id=\'name' + rowId + "\'"; //if (Number(rowId) < 5) { return ' colspan=2' } } }, { name: 'nameB', index: 'nameB', width: 70, cellattr: function(rowId, tv, rawObject, cm, rdata) { //if (Number(rowId) < 5) { return ' style="display:none;"' } } }, { name: 'amount', index: 'amount', width: 100, formatter: 'number', align: 'right', cellattr: function(rowId, tv, rawObject, cm, rdata) { //合并单元格 return 'id=\'amount' + rowId + "\'"; } }, { name: 'tax', index: 'tax', width: 70, formatter: 'number', align: 'right', cellattr: function(rowId, tv, rawObject, cm, rdata) { //合并单元格 return 'id=\'tax' + rowId + "\'"; } }, { name: 'total', index: 'total', width: 120, formatter: 'number', align: 'right', cellattr: function(rowId, tv, rawObject, cm, rdata) { //合并单元格 return 'id=\'total' + rowId + "\'"; } }, { name: 'closed', index: 'closed', width: 110, align: 'center', formatter: 'checkbox', edittype: 'checkbox', editoptions: { value: 'Yes:No', defaultValue: 'Yes' } }, { name: 'ship_via', index: 'ship_via', width: 120, align: 'center', formatter: 'select', edittype: 'select', editoptions: { value: 'FE:FedEx;TN:TNT;IN:Intim', defaultValue: 'Intime' }, //①给当前想合并的单元格设置id cellattr: function(rowId, tv, rawObject, cm, rdata) { return 'id=\'ship_via' + rowId + "\'"; } }, { name: 'note', index: 'note', width: 100, sortable: false } ], rowNum: 15, rowList: [10, 15, 20, 30], pager: '#pager', gridview: true, rownumbers: true, sortname: 'invdate', viewrecords: true, sortorder: 'desc', caption: 'Just simple local grid', height: '100%', gridComplete: function() { //②在gridComplete调用合并方法 var gridName = "list"; jqGridMerger(gridName, 'amount'); jqGridMerger(gridName, 'tax'); jqGridMerger(gridName, 'total'); jqGridMerger(gridName, 'name'); jqGridMerger(gridName, 'ship_via'); /*根据某几列合并*/ // jqGridMerger(gridName, 'total',['amount','tax']); } });
/*根据某几列合并*/
// jqGridMerger(gridName, 'total',['amount','tax']);
用于loadComplete事件中可能会出现Bug,建议在gridComplete事件中合并单元格
string strDataView="[{\"ID\":\"123\",\"Name\":\"Test\"},{\"ID\":\"456\",\"Name\":\"Test2\"}]"; string strResult ="[{\"colname\":" + sbColname.ToString() + "}," + "{\"groupheadername\":" + JsonHelper.GetJson<List<groupHeaders>>(pGroupheadername) + "}," + "{\"colmodels\":" + JsonHelper.GetJson<List<colModel>>(pColmodels) + "}," + "{\"DataView\":{\"page\": \"" + PageIndex + "\", \"total\": \"" + TotalPage + "\",\"records\":\"" + list.Count + "\", \"rows\": " + strDataView.ToString() + "}}]";
//加载数据 $('#datagrid')[0].addJSONData(strData[3].DataView); //开启固定表头表列 colModel.frozen = true jQuery("#datagrid").jqGrid('setFrozenColumns');
//简单的情况下合并单元(后台动态加载后添加事件) var fcCell = function (rowId, value, rawObject, cm, rdata) { return rowId % 2 == 1 ? ' rowspan="2" ' : ' style="display:none" '; }; strData[2].colmodels[3].cellattr = fcCell;
下面方法仅供参考,用不到
//合并列的单元格方法(冻结列单独表格) //gridName 表ID,gridfrozen 冻结表ID,cellName 需合并列,tCellNames 需根据某行合并 ['AreaName'] function jqGridMergerAndFrozen(gridName, gridfrozen, cellName, tCellNames) { if (!tCellNames) { tCellNames = []; } else if (!(tCellNames instanceof Array)) { tCellNames = tCellNames.split(','); } tCellNames.push(cellName); var $gridName = $("#" + gridName); var $gridfrozen = $("#" + gridfrozen); //得到显示到界面的id集合 var mya = $gridName.getDataIDs(); //当前显示多少条 var length = mya.length; //定义合并行数 var rowSpanTaxCount = 1; for (var i = 0; i < length; i += rowSpanTaxCount) { //从上到下获取一条信息 var before = $gridName.jqGrid('getRowData', mya[i]); //定义合并行数 rowSpanTaxCount = 1; for (j = i + 1; j <= length; j++) { //和上边的信息对比 如果值一样就合并行数+1 然后设置rowspan 让当前单元格隐藏(未固定表列) var end = $gridName.jqGrid('getRowData', mya[j]); if (MergerCondition(before, end, tCellNames)) {//before[tCellName] == end[tCellName] rowSpanTaxCount++; //$("td[id='" + cellName + mya[j] + "']").hide(); $("#" + cellName + mya[j], $gridName).hide(); $("#" + cellName + mya[j], $gridfrozen).hide(); } else { break; } //$("td[id='" + cellName + mya[i] + "']").attr("rowspan", rowSpanTaxCount); $("#" + cellName + mya[i], $gridName).attr("rowspan", rowSpanTaxCount); $("#" + cellName + mya[i], $gridfrozen).attr("rowspan", rowSpanTaxCount); } } }
导出Excel、PDF……
//引用 jszip.min.js /*此插件的限制-注意: loadonce: true, 必须设为true;datatype: "json", 测试必须设为json,设为local就不行,其他数据格式未使用否则导出excel只有列头;中文命名可能部分浏览器或系统是乱码*/ $("#export").on("click", function(){ $("#jqGrid").jqGrid("exportToExcel",{ includeLabels : true, includeGroupHeader : true, includeFooter: true, fileName : "jqGridExport.xlsx", maxlength : 40 // maxlength for visible string data }) })
导出Excel方案2 详见方案4>>
禁止选中
onSelectAll: function (rowids, status) { if (status == true) { var $datagrid = $(this); var rowIds = $datagrid.jqGrid('getDataIDs');//获取所有行id for (var i = 0; i < rowIds.length; i++) { rowData = $datagrid.jqGrid("getRowData", rowIds[i]); if (rowData.Wo != "") { $datagrid.jqGrid("setSelection", rowIds[i], false);//设置该行不能被选中。 } } } }, onSelectRow: function (rowid, status) { if (status == true) { var $datagrid = $(this); var rowData = $datagrid.jqGrid('getRowData', rowid); if (rowData.Wor != "") {//禁用条件 $datagrid.jqGrid("setSelection", rowid, false);//设置该行不能被选中。 } } }, gridComplete: function () { var $datagrid = $(this); var rowIds = $datagrid.jqGrid('getDataIDs'); for (var k = 0; k < rowIds.length; k++) { var curRowData = $datagrid.jqGrid('getRowData', rowIds[k]);//获取指定id所在行的所有数据. if (curRowData.p == "") { $("#" + rowIds[k] + "").find(":checkbox").remove(); } else { if (parseInt(curRowData.Pr) > 0 || curRowData.Wo != "") { $("#" + rowIds[k] + "").find(":checkbox").remove(); } } } }
//插入辅助行 分页的情况下 setTimeout(function () { var tm = $(".ui-paging-info").html(); var $datagrid = $("#datagrid"); var lgt = lg; if (strData[2].DataView.footerrows) { for (var i = 0; i < strData[2].DataView.footerrows.length; i++) { lgt += 1; $datagrid.jqGrid('addRowData', lgt, strData[2].DataView.footerrows[i], 'last'); } } $(".ui-paging-info").html(tm); setTimeout(function () { $("#datagrid tr:gt(" + lg + ") td").css({ "background-color": "#f6f6f6" }); var $td = $("#datagrid_frozen tr:gt(" + lg + ") td"); $td.css({ "background-color": "#f6f6f6" }); $td.filter(":even").html(''); }, 100); }, 300); //尾部统计行 单行 footerrow: true, //$("#datagrid").jqGrid("footerData", "set", { "DataTime": "--合计1--", "wt1": "--合计2--" }) //顶部统计行 summaryData
/*其他配置示例*/ //重新加载数据 $.jgrid.gridUnload('#datagrid'); jqGrid 清除数据有以下几种方式: 使用 $("#grid").jqGrid('clearGrid') 方法清除所有数据。 使用 $("#grid").jqGrid('setGridParam', {data: []}) 方法设置空数据数组,然后调用 $("#grid").trigger("reloadGrid") 重新加载数据。 使用 $("#grid").jqGrid('setCaption', '') 方法清除表格标题。 使用 $("#grid").jqGrid('setColProp', {name:'columnName', label:''}) 方法清除指定列的标签。 使用 $("#grid").jqGrid('setRowData', rowid, null) 方法清除指定行的数据。
formatter