How do I able to download excel file by calling from ajax call to asp.net webform (web method) without creating file in server? I have done this in asp.mvc by saving epplus excel package to memory stream which then saved into Tempdata. on Success call I retrieved the data memory stream from temp data and write it out. I do not know how do i achieve something like this in web method? Currently I am doing this by creating a excel file in server and then retrieved the file and write the file out.
Below is my code.
[WebMethod] public static string DownloadExcelReport(List<MyReport> reports, string fileName) { ValidationMessage vm = new ValidationMessage(); string urlToInvoke; try { try { ListtoDataTableConverter converter = new ListtoDataTableConverter(); DataTable dt = converter.ToDataTable(reports); string xlfileName = fileName + "_" + DateTime.Now.ToString("yyyyMMddHHmmssfff") + ".xlsx"; string filePath = fileLocation + xlfileName; using (ExcelPackage xlPackage = new ExcelPackage(new FileInfo(filePath))) { ExcelWorksheet ws = xlPackage.Workbook.Worksheets.Add("AdhocStaffReport"); ws.Cells("A1").LoadFromDataTable(dt, true); xlPackage.Save(); } urlToInvoke = Convert.ToString("~/ExcelDownLoadForm.aspx?fn=") + xlfileName; } catch (Exception ex) { vm.stat = 2; vm.message = "Internal Server Error"; throw; } return JsonConvert.SerializeObject(new { Success = true, redirectUrl = VirtualPathUtility.ToAbsolute(urlToInvoke) }); } catch (Exception ex) { //log ex return JsonConvert.SerializeObject(vm); } } //IN ExcelDownLoadForm.Aspx.cs protected void Page_Load(object sender, System.EventArgs e) { try { string fileName = Request.QueryString("fn"); string filePath = ConfigurationManager.AppSettings("ExcelFilePath") + fileName; Response.ContentType = ContentType; Response.AppendHeader("content-disposition", "attachment; filename=" + Path.GetFileName(filePath)); Response.TransmitFile(filePath); Response.Flush(); if (File.Exists(filePath)) File.Delete(filePath); Response.End(); } catch (Exception ex) { if (ex.Message == "Thread was being aborted.") string eatException = ex.Message; // this Exception is due to Response.End() method else { throw; } } }
var
This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)