Click here to Skip to main content
15,867,686 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
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.


What I have tried:

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;
                }
            }
    
}
Posted
Comments
j snooze 26-Feb-19 17:12pm    
asp.net code is run on the web server. If you want everything on the client either make a client app, or figure out how to create an excel file using all javascript. Web pages are meant to talk back and forth between server and client.
That is if I read your request correctly.
istudent 26-Feb-19 23:59pm    
Question is not about creating excel file. Question is about how to able to do ajax call to a method on server and on success able to download the file.
istudent 27-Feb-19 0:01am    
I have also mentioned how I have achieved same in mvc framework but I am clueless to do so in web form. I have done by creating a file in server but I want to create in memory stream instead of creating file.
j snooze 27-Feb-19 17:02pm    
Sorry, my misunderstanding.
Maybe this link will help you out. Looks like it might be as simple as putting the [WebMethod] attribute on the server page method you want to call.

https://stackoverflow.com/questions/5331986/how-to-use-ajax-with-asp-net-webforms
istudent 1-Mar-19 15:22pm    
If you go through the code, I am calling PageMethod(WebMethod). That's not the my question was. But Thank you.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900