我正在研究MVC4项目.我有Devexpress报告工具栏,我有一个自定义按钮导出到excel,因为内置功能有单元合并问题.
无论如何点击该自定义按钮..我想运行导出到Excel代码..但它的工作...我的意思是它返回正确的HTML但不要求提示保存文件/下载文件,可能是因为ajax调用. ..
这是ajax调用的代码
function ReportToolbar_ItemClick(s, e) { debugger; if (e.item.name == 'btnCustomeExport') { // $.post('@Url.Action("ExportToExcel", "Report")'); $.ajax({ url: "@Url.Action("ExportToExcel", "Report")", type: "POST", success: function (data, textStatus, jqXHR) { //data: data from server alert('success'); }, error: function (jqXHR, textStatus, errorThrown) { alert('error'); } }); } }
和控制器代码:
public ActionResult ExportToExcel() { try { GridView GridView1 = new GridView(); Response.ClearContent(); Response.Buffer = true; Response.AddHeader("content-disposition", string.Format("attachment; filename={0}", "EmployeesData.xls")); Response.ContentType = "application/ms-excel"; StringWriter stringWriter = new StringWriter(); HtmlTextWriter htmlTextWriter = new HtmlTextWriter(stringWriter); GridView1.AllowPaging = false; GridView1.DataSource = ReportExecutor.GetShopReportExportData(DateTime.Now, DateTime.Now); GridView1.DataBind(); //This will change the header background color GridView1.HeaderRow.Style.Add("background-color", "#FFFFFF"); //This will apply style to gridview header cells for (int index = 0; index < GridView1.HeaderRow.Cells.Count; index++) { GridView1.HeaderRow.Cells[index].Style.Add("background-color", "#d17250"); } int index2 = 1; //This will apply style to alternate rows foreach (GridViewRow gridViewRow in GridView1.Rows) { gridViewRow.BackColor = Color.White; if (index2 <= GridView1.Rows.Count) { if (index2 % 2 != 0) { for (int index3 = 0; index3 < gridViewRow.Cells.Count; index3++) { gridViewRow.Cells[index3].Style.Add("background-color", "#eed0bb"); } } } index2++; } GridView1.RenderControl(htmlTextWriter); Response.Write(stringWriter.ToString()); Response.End(); return Json(new { successCode = "1" }); } catch (Exception e) { return Json(new { successCode = "0" }); } }
如果我调试代码..我得到结果stringWriter
但仍然无法看到保存/下载选项??
由于它没有显示您发送任何数据而不是ajax尝试:
window.location= "@Url.Action("ExportToExcel", "Report")";
或者只使用<a>
标签中的urlhref