Click here to Skip to main content
15,885,366 members
Articles / Web Development / ASP.NET
Tip/Trick

ASP.NET Export Excel - Show/Hide Loading Image

Rate me:
Please Sign up or sign in to vote.
4.00/5 (15 votes)
2 Aug 2016CPOL2 min read 63K   587   9   22
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

C#
 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

HTML
<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

JavaScript
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

Image 1

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, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer Infosys
India India
All is well Smile | :)

Comments and Discussions

 
PraisePerfect! Thank you very much!! Pin
Member 158555195-Dec-22 22:33
Member 158555195-Dec-22 22:33 
GeneralRe: Perfect! Thank you very much!! Pin
Karthik_Mahalingam5-Dec-22 22:39
professionalKarthik_Mahalingam5-Dec-22 22:39 
GeneralMy vote of 5 Pin
Member 158555195-Dec-22 22:31
Member 158555195-Dec-22 22:31 
QuestionExcellent example, thank you Pin
Intervman25-Oct-21 11:28
Intervman25-Oct-21 11:28 
Questionthank you Pin
Pragu Patel29-Jun-20 21:38
Pragu Patel29-Jun-20 21:38 
AnswerThank you Pin
agieos15-Dec-18 2:47
agieos15-Dec-18 2:47 
Questionthank Pin
Đường Vũ26-Feb-18 17:19
Đường Vũ26-Feb-18 17:19 
BugExcellent example, but has bug Pin
Member 1292754629-Dec-16 11:35
Member 1292754629-Dec-16 11:35 
GeneralRe: Excellent example, but has bug Pin
Karthik_Mahalingam2-Jan-17 19:20
professionalKarthik_Mahalingam2-Jan-17 19:20 
GeneralRe: Excellent example, but has bug Pin
smirosh7-Aug-19 5:48
smirosh7-Aug-19 5:48 
PraiseAmazing code. Thank You Pin
Member 1208152129-Sep-16 3:09
Member 1208152129-Sep-16 3:09 
GeneralRe: Amazing code. Thank You Pin
Karthik_Mahalingam29-Sep-16 3:25
professionalKarthik_Mahalingam29-Sep-16 3:25 
Questiongif image hang up Pin
nikhilkahre4-Aug-16 8:24
nikhilkahre4-Aug-16 8:24 
AnswerRe: gif image hang up Pin
Karthik_Mahalingam4-Aug-16 16:19
professionalKarthik_Mahalingam4-Aug-16 16:19 
AnswerRe: gif image hang up Pin
Karthik_Mahalingam27-Sep-16 5:40
professionalKarthik_Mahalingam27-Sep-16 5:40 
General[My vote of 2] Not an true Export to Excel Pin
AnvilRanger2-Aug-16 2:16
AnvilRanger2-Aug-16 2:16 
GeneralRe: [My vote of 2] Not an true Export to Excel Pin
Karthik_Mahalingam2-Aug-16 2:46
professionalKarthik_Mahalingam2-Aug-16 2:46 
GeneralRe: [My vote of 2] Not an true Export to Excel Pin
AnvilRanger4-Aug-16 9:02
AnvilRanger4-Aug-16 9:02 
Suggestion[My vote of 1] You shall cite the original source Pin
yxhu1-Aug-16 23:03
yxhu1-Aug-16 23:03 
GeneralRe: Pin
Karthik_Mahalingam2-Aug-16 0:31
professionalKarthik_Mahalingam2-Aug-16 0:31 
PraiseNice Article.. Pin
Santosh Kokatnur31-Jul-16 22:30
Santosh Kokatnur31-Jul-16 22:30 
GeneralRe: Nice Article.. Pin
Karthik_Mahalingam31-Jul-16 22:51
professionalKarthik_Mahalingam31-Jul-16 22:51 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.