Learn how to a build a cloud-first strategyRegister Now

x
?
Solved

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

Posted on 2011-10-14
8
Medium Priority
?
334 Views
Last Modified: 2012-06-27
I have an asp.net 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

Example
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.Clear();
                  Response.AddHeader("content-disposition", "attachment;filename=MyPicks.xls");
                  Response.Charset = "";
                  Response.ContentType = "application/vnd.ms-excel";
                  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");
                  myGrid.RenderControl(htmlWrite);
                  Response.Write(stringWrite.ToString());
                  Response.End();
            }
0
Comment
Question by:countrymeister
  • 4
  • 3
8 Comments
 
LVL 7

Expert Comment

by:gopaltayde
ID: 36973038
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.
0
 
LVL 1

Author Comment

by:countrymeister
ID: 36973390
I do not want crystal reports, also crystal reports is somthing my company will not purchase.
0
 
LVL 83

Expert Comment

by:CodeCruiser
ID: 36976595
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)

http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.gridview.caption.aspx
0
Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

 
LVL 1

Author Comment

by:countrymeister
ID: 36976636
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
0
 
LVL 83

Expert Comment

by:CodeCruiser
ID: 36976638
You can open a new window which does the response.write so it does not mess up with ajax.
0
 
LVL 1

Author Comment

by:countrymeister
ID: 36976658
CodeCruiser

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()
        Try


            Dim strFilePath As String = String.Empty
            strFilePath = Server.MapPath("~/Excel/") + "ExcelFileName" + ".xls"

            If (File.Exists(strFilePath)) Then
                File.Delete(strFilePath)
            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)
            dgCriticalResults.RenderControl(oHtmlTextWriter)
            objStreamWriter.WriteLine(strHeader)
            objStreamWriter.WriteLine(strHeader1)
            objStreamWriter.WriteLine(oStringWriter.ToString())
            objStreamWriter.Close()
           
            Dim sb As StringBuilder = New StringBuilder("")
            sb.Append("window.open('" & 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

0
 
LVL 83

Accepted Solution

by:
CodeCruiser earned 2000 total points
ID: 36976664
I think it would be more suitable to have a button outside updatepanel that calls this export functionality.
0
 
LVL 1

Author Comment

by:countrymeister
ID: 36976684
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.
0

Featured Post

Prep for the ITIL® Foundation Certification Exam

December’s Course of the Month is now available! Enroll to learn ITIL® Foundation best practices for delivering IT services effectively and efficiently.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

How to get Spreadsheet Compare 2016 working with the 64 bit version of Office 2016
Microsoft's Excel has many features that most people will never need nor take advantage of.  Conditional formatting is one feature that you may find a necessity once you start using it.
This Micro Tutorial demonstrate the bugs in Microsoft Excel for Mac with Pivot Charts.
This Micro Tutorial will demonstrate how to create pivot charts out of a data set. I also added a drop-down menu which allows to choose from different categories in the data set and the chart will automatically update.

804 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