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

Link ASP.NET Data Grid to Microsoft Excel in the client side

0.00/5 (No votes)
12 Dec 2004 1  
How to use JavaScript to export HTML table into Excel work sheet?

Sample Image - 6.jpg

Introduction

I was playing with internet explorer context menu, suddenly I noted that I have menu item called "export to Microsoft Excel".

:)

When I clicked on this command it is transferred the contents of the selected table to Microsoft excel.

How did I steal the code?

To guess what was happing on when I clicked on the context menu item, I used the IE feature, break at next statement (from menu item choose View-> Script Debugger->Break at Next Statement ), and made a small table and as I clicked on the menu and I got the VBScript file in Visual Studio .NET.

How did I link the datagrid with the script?

I have used something called HTC "HTML Components" which is a good thing to learn if you are developing an ASP.NET Server Control. My HTC script is divided in to two parts :

  • First one is how to display a small icon near the datagrid, and that was by
    1. creating HTML image object.
      ImgaElement=this.document.createElement("img")
    2. putting the image near the datagrid table.
      ImgaElement.style.top=this.element.offsetTop-3 
      ImgaElement.style.left=this.element.offsetLeft+offsetWidth-3
  • And the second part is how to plug it to the Microsoft Excel. In this task I did not do anything new but converting the VBS file to JavaScript one and add additional lines for checking the security settings.
    try 
    {
           xlApp= new ActiveXObject("Excel.Application"); 
    } 
    catch(e) 
    {
        alert("Please check the Internet security setting");
            return -1;
    }

How to use it?

  • An important note before using the component is, to enable the "Initialize and script ActiveX controls not marked as safe"

    :)

    in the security tab in the internet security settings.

  • Copy the images and the HTC folders to your web project.
  • Add a the DLL file (DataGridProject.dll) to your references and to the Toolbox controls.

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