Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

ASP.NET Export Excel - Show/Hide Loading Image

0.00/5 (No votes)
2 Aug 2016 1  
Show/hide the loading GIF image while exporting a file from server

Introduction

This tip will explain how to hide the loading gif image after the file is downloaded. It will be helpful when we are using Response Object to export the Excel or any other file format.

Background

Sometimes, while downloading an Excel or any file from an ASP application, it might take some time to generate the file, the delay depends on many factors (file size, loops, server bandwidth, etc.). So we represent the File Generation process using a rotating GIF image next to the button.

But when we are using Response object, we won't get the event after the file is downloaded to the browser, in this case, it will be difficult to hide the loading gif which is being shown on the screen.

This question was frequently asked in the CodeProject's Q&A section and other forums.

The below steps will guide how to Show the Gif while Generating and hide it once the file is completely downloaded.

Steps to Hide the GIF After Download

  • When the download button is clicked, show the loading gif image using onclicentClick event and CSS properties.
  • On the Client click event, invoke a JavaScript method which contains a Setinterval object that monitors for our cookie (created in C# Response object).
  • In the Server button, click Event, create an HttpCookie and append it to the Response object.
  • So when the file is downloaded completely, the Cookie is added to the Page. Now the SetInterval function will capture the cookie and hides the loading Gif image.
  • Note: Whenever the download button is clicked, the previous cookie has to be deleted.

Using the Code

C# Code

 protected void btnExportExcel_Click(object sender, EventArgs e)
  {
    DataTable dt = new DataTable();
    dt = GetDataFromDb();
    System.Threading.Thread.Sleep(3000); // for testing purpose to create 3 seconds delay
    //Create a temp GridView
    GridView gv = new GridView();
    gv.AllowPaging = false;
    gv.DataSource = dt;
    gv.DataBind();
    Response.Clear();
    Response.Buffer = true;
    Response.AddHeader("content-disposition", "attachment;filename=ExcelReport.xls");
    Response.Charset = "";
    Response.ContentType = "application/vnd.ms-excel";
    StringWriter sw = new StringWriter();
    HtmlTextWriter hw = new HtmlTextWriter(sw);
    gv.RenderControl(hw);

    // Append cookie
    HttpCookie cookie = new HttpCookie("ExcelDownloadFlag");
    cookie.Value = "Flag";
    cookie.Expires = DateTime.Now.AddDays(1);
    Response.AppendCookie(cookie);
    // end

    Response.Output.Write(sw.ToString());
    Response.Flush();
    Response.End();
}

HTML/ASPX Code

<table>
           <tr>
               <td>
                   <asp:Button Text="Download" ID="btnExportExcel"
                   OnClientClick="jsShowHideProgress();"
                   runat="server" OnClick="btnExportExcel_Click" />
               </td>
               <td>
                   <img style="display: none" id="imgloadinggif"
                   src="Images/loading.gif" alt="loading.." />
               </td>
           </tr>
       </table>

JavaScript Code

function jsShowHideProgress() {
    setTimeout(function ()
    { document.getElementById('imgloadinggif').style.display = 'block'; }, 200);
    deleteCookie();

    var timeInterval = 500; // milliseconds (checks the cookie for every half second )

    var loop = setInterval(function () {
        if (IsCookieValid())
        { document.getElementById('imgloadinggif').style.display =
        'none'; clearInterval(loop) }

    }, timeInterval);
}

// cookies
function deleteCookie() {
    var cook = getCookie('ExcelDownloadFlag');
    if (cook != "") {
        document.cookie = "ExcelDownloadFlag=;
        Path=/; expires=Thu, 01 Jan 1970 00:00:00 UTC";
    }
}

function IsCookieValid() {
    var cook = getCookie('ExcelDownloadFlag');
    return cook != '';
}

function getCookie(cname) {
    var name = cname + "=";
    var ca = document.cookie.split(';');
    for (var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') {
            c = c.substring(1);
        }
        if (c.indexOf(name) == 0) {
            return c.substring(name.length, c.length);
        }
    }
    return "";
}

Demo

References

Points of Interest

The same logic and code will work in MVC application also with slight code changes.

I was inspired by and simplified the concept from here.

History

  • Initial version, tested in Internet Explorer and Chrome

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here