嗨,我创建了将 Gridview 转换为 excel 文件的导出类。
见下面的代码:
下载FileActionResult 类:
public class DownloadFileActionResult : ActionResult
{
public GridView ExcelGridView { get; set; }
public string fileName { get; set; }
public DownloadFileActionResult(GridView gv, string pFileName)
{
ExcelGridView = gv;
fileName = pFileName;
}
public override void ExecuteResult(ControllerContext context)
{
HttpContext curContext = HttpContext.Current;
curContext.Response.ClearContent();
curContext.Response.AddHeader("content-disposition", "attachment; filename=" + fileName + ".xls");
curContext.Response.ContentType = "application/vnd.ms-excel";
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
ExcelGridView.RenderControl(htw);
curContext.Response.Write(sw.ToString());
curContext.Response.End();
}
}
jQuery-ajax:
function Export(){
var search = {};
search.Name = "MaterialShape";
search.Description = "";
search.Address ="";
var url_ = generateURL("/Home/Download"); //Call Save Controller and pass details entities
$.ajax({
type: "POST",
url: url_,
data: search, //details will act as the Entities Model
traditional: true,
success: function(data) {
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("error: " + XMLHttpRequest.responseText);
},
dataType: 'json'
});
};
搜索参数属性:
public class SearchParams
{
public string Name{ get; set; }
public string Description {get;set;}
public string Address{get;set;}
...
}
然后我在我的控制器上实现它:
//Export to excel
public ActionResult Download(SearchParam param)
{
List<Lookup> lookupList = data.GetLookup(param);
var grid = new System.Web.UI.WebControls.GridView();
grid.DataSource = lookupList;
grid.DataBind();
return new DownloadFileActionResult(grid, "test");
}
当我手动输入控制器 url 时它正在工作(没有搜索参数值)
http://localhost:54928/Home/Download
或使用 html.action 链接
<%= Html.ActionLink("Home", "/Download", "Home")%>
但是当我使用ajax调用时它不起作用
<img src="<%=Url.Content("~/Images/export.png")%>" id="Img1" onclick="Export();" alt="Export" />
我真的需要使用。
我在这里遗漏了一些东西..有什么想法吗?
感谢问候