Exporting data grid to excel, also add the filter criteria on the first line on the excel workbook

Posted on 2011-10-14
Last Modified: 2012-06-27
I have an application where I would like to export the contents of the datagrid to excel.
I have seen a few examples where the datagrid is exported, but in my case I want a header row on the first line of the excel workseet with the filters that were used

StartDate 10/01/2011 - EndDate 10/31/2011
Grid data follows

Any code sample would be great.

I saw this example
private void LinkButton1_Click(object sender, System.EventArgs e)
                  Response.AddHeader("content-disposition", "attachment;filename=MyPicks.xls");
                  Response.Charset = "";
                  Response.ContentType = "application/";
                  System.IO.StringWriter stringWrite = new System.IO.StringWriter();
                  System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);

                  System.Web.UI.WebControls.DataGrid myGrid =  (System.Web.UI.WebControls.DataGrid)PlaceHolder1.FindControl("DataGrid1");
Question by:countrymeister
    LVL 7

    Expert Comment

    Not the actual solution, but the work around is -
    use crystal reports for .net (which is free with .net). Build a report with your stored procedure, the one which you use to bind the gridview control. Now export the ReportDocument object to any format without any pain.
    LVL 1

    Author Comment

    I do not want crystal reports, also crystal reports is somthing my company will not purchase.
    LVL 83

    Expert Comment

    What version of .NET are you using? The mention of "DataGrid1" has got me worried. If its a GridView, set its Caption property to the filter text and then it would render on top in Excel (hopefully)
    LVL 1

    Author Comment

    Hi ! CodeCruiser

    I am fine to use a Gridview instead of using a DataGrid, but what I am facing is that Response.Write does not bode well with AJAXed pages.
    Also I want to stay away from Excel Interop dll's any other suggestion would be geat
    LVL 83

    Expert Comment

    You can open a new window which does the response.write so it does not mess up with ajax.
    LVL 1

    Author Comment


    I did venture into that direction. It gives me an error stating Acces denied.
    Please note that I do not have excel installed on the web server, Is this needed to be installed?
    Code is attached inline.

    I do see the excel file being created, and Everyone is granted Full permissions to the Excel folder.
    Protected Sub ExportToExcel()
                Dim strFilePath As String = String.Empty
                strFilePath = Server.MapPath("~/Excel/") + "ExcelFileName" + ".xls"
                If (File.Exists(strFilePath)) Then
                End If
                Dim oStringWriter As System.IO.StringWriter = New StringWriter()
                Dim oHtmlTextWriter As System.Web.UI.HtmlTextWriter = New HtmlTextWriter(oStringWriter)
                Dim objStreamWriter As StreamWriter
                Dim strHeader As String = "XYZ Report"
                Dim strHeader1 As String = "StartDate: " & txtStartDate.Text & "  EndDate: " & txtEndDate.Text
                objStreamWriter = File.AppendText(strFilePath)
                Dim sb As StringBuilder = New StringBuilder("")
                sb.Append("'" & strFilePath & "','mywindow','width=400,height=400,resizable=1,top=50,left=50,scrollbars=1');")
                ScriptManager.RegisterClientScriptBlock(Me.Page, Me.Page.GetType(), Me.ClientID, sb.ToString(), True)
            Catch ex As Exception
                'Handle Exception
                Dim strError As String = ex.Message()
            End Try
        End Sub

    Open in new window

    LVL 83

    Accepted Solution

    I think it would be more suitable to have a button outside updatepanel that calls this export functionality.
    LVL 1

    Author Comment

    Code cruiser

    I did try that too.

    I am using Master page which has AJAX and then my child page uses the master page.
    I pulled out the button from the updatepanel and the same error still exits.

    Write Comment

    Please enter a first name

    Please enter a last name

    We will never share this with anyone.

    Featured Post

    Looking for New Ways to Advertise?

    Engage with tech pros in our community with native advertising, as a Vendor Expert, and more.

    Approximate matching with VLOOKUP and MATCH seems to me to be a greatly under-used technique, and one which is vital for getting good performance out of large lookups. Until recently I would always have advised using an exact match for simplicity an…
    Workbook link problems after copying tabs to a new workbook? David Miller (dlmille) Intro Have you either copied sheets to a new workbook, and after having saved and opened that workbook, you find that there are links back to the original sou…
    The view will learn how to download and install SIMTOOLS and FORMLIST into Excel, how to use SIMTOOLS to generate a Monte Carlo simulation of 30 sales calls, and how to calculate the conditional probability based on the results of the Monte Carlo …
    The viewer will learn how to create two correlated normally distributed random variables in Excel, use a normal distribution to simulate the return on different levels of investment in each of the two funds over a period of ten years, and, create a …

    761 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    10 Experts available now in Live!

    Get 1:1 Help Now