download a file through ajax request in asp.net MVC 4
I am trying to download the data to excel using ajax request, I have applied few approaches which were mentioned but no luck
Referred to this article Export DataTable (DataSet) to Excel file in ASP.Net MVC but no luck
function downloadReport() {
var data = JSON.stringify({
'startDt': $("#eventFromDate").val(),
'endDt': $("#eventTodate").val()
});
$.ajax({
type: "POST",
url: "/EventReport/DonwloadExcel",
data: data,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess,
failure: function (response) {
alert(response.d);
},
error: function (response) {
alert(response.d);
}
});
}
public ActionResult DonwloadExcel(DateTime startDt, DateTime endDt)
{
ReportableEventRepository reportableEventRepository = new ReportableEventRepository();
MemoryStream stream = reportableEventRepository.DownloadToExcel(startDt, endDt);
return File(stream.ToArray(), "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "Grid.xlsx");
}
public void DownloadToExcel(DateTime startDt, DateTime endDate)
{
using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["BMA"].ConnectionString))
{
using (SqlCommand cmd = new SqlCommand("up_ReportableEventData", con))
{
cmd.Parameters.AddWithValue("@StartDt", startDt.ToString("yyyy-MM-dd"));
cmd.Parameters.AddWithValue("@EndDt", endDate.ToString("yyyy-MM-dd"));
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Connection = con;
cmd.CommandType = CommandType.StoredProcedure;
sda.SelectCommand = cmd;
using (DataTable dt = new DataTable("ReportableEvent"))
{
sda.Fill(dt);
using (XLWorkbook wb = new XLWorkbook())
{
wb.Worksheets.Add(dt);
wb.Style.Alignment.Horizontal = XLAlignmentHorizontalValues.Center;
wb.Style.Font.Bold = true;
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.Buffer = true;
HttpContext.Current.Response.Charset = "";
HttpContext.Current.Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
HttpContext.Current.Response.AddHeader("content-disposition", "attachment;filename= EmployeeReport.xlsx");
using (MemoryStream MyMemoryStream = new MemoryStream())
{
wb.SaveAs(MyMemoryStream);
MyMemoryStream.WriteTo(HttpContext.Current.Response.OutputStream);
HttpContext.Current.Response.Flush();
HttpContext.Current.Response.End();
}
}
}
}
}
}
}