客户端
function PostAndGetFileByUrl(url,type,postdata) {
var temp;
$.ajax({
url: url,
type: type,
data: {keyword:postdata},
async: true,
dataType: "Text",
success: function (data) {
downloadFile(data);
}
});
return temp;
}
function btn_export()
{
var $gridList = $("#gridList");
var rowData = $gridList.jqGrid('getGridParam','selarrrow');
PostAndGetFileByUrl("/RunManage/EnvData/WriteToExcel", "POST", rowData.join(","));
}
function downloadFile(url) {
try {
var elemIF = document.createElement("iframe");
elemIF.src = url;
elemIF.style.display = "none";
document.body.appendChild(elemIF);
} catch (e) { }
} <a id="NF-export" class="btn btn-primary" onclick="btn_export()"><i class="fa fa-plus"></i>导出XLS</a>
使用到了npoi库,请自行引用
[HttpPost]
[HandlerAjaxOnly]
public ActionResult WriteToExcel(string keyword)
{
DataTable dt = new DataTable();
dt.Columns.Add("AAAA");
dt.Columns.Add("BBBB");
List<ItemEntity> dataList = EnvDataApp.GetListByKeywordArray(keyword);//请写自己的获取List方法
foreach (var item in dataList)
{
DataRow dr = dt.NewRow();
dr["AAAA"] = item.F_ID;
dr["BBBB"] = item.F_FullName;
dt.Rows.Add(dr);
}
NPOIExcel npoiexel = new NPOIExcel(); string fileDir = DateTime.Now.ToString("yyyyMMdd");
string fileName = "G" + Guid.NewGuid().ToString("N") + ".xls";
string destDir = Server.MapPath(@"/XlsTemp") + "\\" + fileDir + "\\";
if (!Directory.Exists(destDir))
{
Directory.CreateDirectory(destDir);
}
npoiexel.ToExcel(dt, "数据", "Sheet1", destDir + fileName);
return Content("/XlsTemp/" + fileDir + "/" + fileName);
}
}
注:这是一种写文件到磁盘方法,可以改造下,支持大文件,定时查询生成状态,可以重复下载。如果简单的excel可以直接Response.Write