EasyUI Datagrid 导出到Excel (不含frozenColumns列)
一、首先将dg的columns(Excel的表头)行拼装成<table>标签的<tr>作为第一行,并且定义一个数组接受这组值,
1 var tableString = '<table border="1" bordercolor="#D7D7D7">'; 2 var columns = printDatagrid.datagrid("options").columns; // 得到columns对象 3 var nameList = new Array();//定义一个数组接受columns的所有值 4 // 载入title 5 if (typeof columns != 'undefined' && columns != '') { 6 $(columns).each(function (index) { 7 tableString += '<tr>'; 8 for (var i = 0; i < columns[index].length; ++i) { 9 if (!columns[index][i].hidden) { 10 tableString += '<th'; 11 if (typeof columns[index][i].field != 'undefined' && columns[index][i].field != '') { 12 nameList.push(columns[index][i]); 13 } 14 tableString += '>' + columns[index][i].title + '</th>'; 15 } 16 } 17 tableString += '</tr>'; 18 }); 19 }
注:printDatagrid是dg的JQ对象
二、读取dg正文内容;
1 // 载入内容 2 var rows = printDatagrid.datagrid("getRows"); // 这段代码是获取当前页的所有行 3 for (var i = 0; i < rows.length; ++i) { 4 tableString += '<tr>'; 5 for (var j = 0; j < nameList.length; ++j) { 6 tableString += '<td'; 7 tableString += '>'; 8 if (typeof (rows[i][nameList[j].field]) == "undefined") { 9 tableString += " " 10 } else { 11 tableString += rows[i][nameList[j].field]; 12 } 13 tableString += '</td>'; 14 } 15 tableString += '</tr>'; 16 } 17 tableString += '</table>'
三、由于ajax的返回类型没有流类型,所以用提交form表单的形式向后台传数据,其中参数要用encodeURI( )转码,否则html标签是传不到后台的
var options = $("#dg").datagrid('getPager').pagination('options'); var f = $('<form action="../handler/dgtoexcel.ashx" method="post" id="fm1"></form>'); var i = $('<input type="hidden" id="contexts" name="contexts" />'); //主题内容 var pn = $('<input type="hidden" id="txtname" name="txtname" />'); //文件名 i.val(encodeURI(tableid)); i.appendTo(f); pn.val(encodeURI(options.pageNumber)); pn.appendTo(f); f.appendTo(document.body).submit(); 提交表单
后台就很简单了,request获取参数并且对参数UrlEncode解码,然后输出文件流 文件名拓展名得是 .xls
1 public void Export(string Contents, string name) 2 { 3 try 4 { 5 HttpContext.Current.Response.ClearContent(); 6 HttpContext.Current.Response.Charset = "GB2312"; 7 HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.UTF8; 8 HttpContext.Current.Response.AddHeader("content-disposition", "attachment; filename=" + HttpUtility.UrlEncode(name, System.Text.Encoding.UTF8).ToString() + ".xls"); 9 HttpContext.Current.Response.ContentType = "application/excel"; 10 HttpContext.Current.Response.Write(Contents); 11 HttpContext.Current.Response.Flush(); 12 } 13 catch (Exception) 14 { 15 16 throw; 17 } 18 finally 19 { 20 HttpContext.Current.Response.ClearContent(); 21 HttpContext.Current.Response.Close(); 22 } 23 }
有什么不对的地方或建议 欢迎提出来!共同进步!