2
我正在MVC4项目。我有Devexpress报告工具栏,我有一个自定义按钮导出为Excel,因为内置函数有单元合并问题。导出到excel使用jquery ajax调用
反正就点击那个自定义按钮..我想运行导出到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使用的网址?只需在浏览器中打开网址....将强制下载和浏览器不会改变页面 – charlietfl
我该怎么做?可以请详细说明..或一些例子/参考 – Mahajan344