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