Geeks With Blogs

@azamsharp
  • azamsharp The WWDC app says that there are new videos but there is nothing under videos!!! about 559 days ago
  • azamsharp Can I post my opinion on iOS 7 Beta or is it under NDA or something? about 559 days ago
  • azamsharp iOS 7 BETA installed successfully! about 559 days ago
  • azamsharp iOS 7 BETA installed! Now restoring! I am on NET10 which uses AT&T network. Hopefully 3G will still work! Lets c.. about 559 days ago
  • azamsharp The missing of button borders in Xcode 5 makes it hard to determine the clickable area. about 559 days ago
  • azamsharp I might wait for iOS to be released before I can put it on my device! Don't want a bricked or unstable device! about 559 days ago
  • azamsharp Android has many features that no one uses, number of versions that no one upgrades to and thousands of apps that no one pays for. about 559 days ago
  • azamsharp Maybe it is just me but the new iOS 7 UI looks like Windows Phone 8 UI! #maybeIamCrazy about 560 days ago
  • azamsharp Anyone using H20 network upgraded to iOS 7 BETA Keep me updated if you face any problems. about 560 days ago
  • azamsharp @merowing_ You already downloaded it! I cannot even load the developer's website! :( about 560 days ago

AzamSharp Some day I will know everything. I hope that day never comes.

Here is the complete code to Export GridView to Excel:

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient; 

public partial class ExportGridView : System.Web.UI.Page
{
    
protected void Page_Load(object sender, EventArgs e)
    {
        
if (!Page.IsPostBack)
        {
            GridView1.DataSource = BindData();
            GridView1.DataBind(); 
        }
    }

    

    
private string ConnectionString
    {

        
get return @"Server=localhost;Database=Northwind;
        Trusted_Connection=true"; }

    }

    

    
private DataSet BindData()
    {
        
// make the query 
        
string query = "SELECT * FROM Categories";
        SqlConnection myConnection = 
new SqlConnection(ConnectionString);
        SqlDataAdapter ad = 
new SqlDataAdapter(query, myConnection);
        DataSet ds = 
new DataSet();
        ad.Fill(ds, "Categories");
        
return ds;

    }




    
protected void Button1_Click(object sender, EventArgs e)
    {
        Response.Clear();

        Response.AddHeader("content-disposition", "attachment;
        filename=FileName.xls");

        Response.Charset = "";

        
// If you want the option to open the Excel file without saving than

        // comment out the line below

        // Response.Cache.SetCacheability(HttpCacheability.NoCache);

        
Response.ContentType = "application/vnd.xls";

        System.IO.StringWriter stringWrite = 
new System.IO.StringWriter();

        System.Web.UI.HtmlTextWriter htmlWrite =
        
new HtmlTextWriter(stringWrite);

        GridView1.RenderControl(htmlWrite);

        Response.Write(stringWrite.ToString());

        Response.End();

    }

    
public override void VerifyRenderingInServerForm(Control control)
    {

        
// Confirms that an HtmlForm control is rendered for the
        
specified ASP.NET server control at run time.

    }
}

powered by IMHO

 

Posted on Wednesday, December 21, 2005 11:06 PM | Back to top


Comments on this post: Export GridView to Excel Complete Code!

# re: Export GridView to Excel Complete Code!
Requesting Gravatar...
I had to set the content type to

"application/vnd.ms-excel"

to get this to work on my machine, go figure!
Left by Brian on Dec 27, 2005 5:51 AM

# re: Export GridView to Excel Complete Code!
Requesting Gravatar...
HI, thanks for your code.
When i use it though i get this error
RegisterForEventValidation can only be called during Render();

any ideas?
thanks
s
Left by Steve on Apr 02, 2006 6:58 AM

# re: Export GridView to Excel Complete Code!
Requesting Gravatar...
Thanks a ton for posting your code, it made my life as an ASP newbie a whole lot easier. (and now for the cry for help) Is there an easy way to remove the formatting from the resulting .xls file?
Left by Tommy on Apr 24, 2006 6:22 PM

# re: Export GridView to Excel Complete Code!
Requesting Gravatar...
Hi,

What type of formatting are you trying to remove?

Left by azamsharp on Apr 24, 2006 6:25 PM

# re: Export GridView to Excel Complete Code!
Requesting Gravatar...
When I open the .xls file it applies all the row color formatting from the gridview but not in a very nice way, the colors are too dark and the text id not visable through it. Right now I just select all, format cells, and select "no color" and it works. I'm just wondering if there is an easy way to d/l the file info without the row colors.
Left by Tommy on Apr 25, 2006 8:39 AM

# re: Export GridView to Excel Complete Code!
Requesting Gravatar...
I tried to export unicode characters, and set Response.Charset = "utf-8", but it is not working.

Anyone knows something about this?

Thanks.
Left by Yanco on May 09, 2006 6:10 AM

# re: Export GridView to Excel Complete Code!
Requesting Gravatar...
Geting Error

Control 'GVGroup' of type 'GridView' must be placed inside a form tag with runat=server.
Left by Narayanan on May 14, 2006 4:55 AM

# re: Export GridView to Excel Complete Code!
Requesting Gravatar...
When ever i click on Export Button My Whole Page is Exported Including Gridview

Any body knows whats the solution to this
Left by Asif on May 16, 2006 4:05 AM

# re: Export GridView to Excel Complete Code!
Requesting Gravatar...
i still have an error:

RegisterForEventValidation can only be called during Render();

anyone knows about it?..
Left by fritz on May 24, 2006 1:30 PM

# re: Export GridView to Excel Complete Code!
Requesting Gravatar...
Hi,

Guys if you control is inside some other control then you need to get the control out and export it. Take a look at this article in which I explained that how you can export the GridView control which is inside the FormView control.

http://gridviewguy.com/ArticleDetails.aspx?articleID=182
Left by azamsharp on May 24, 2006 3:57 PM

# re: Export GridView to Excel Complete Code!
Requesting Gravatar...
When I try this it only takes me to another web page that says the page cannot be opened. Any suggestions??
Left by marko on May 31, 2006 11:12 AM

# re: Export GridView to Excel Complete Code!
Requesting Gravatar...
Hi,

Check out my video tutorial in which I explained step by step on how to export the GridView to Excel. You can view the video at the following link. (Make sure to plug in the headphones since the voice quality is not good).

http://gridviewguy.com/ArticleDetails.aspx?articleID=175

Left by AzamSharp on May 31, 2006 11:15 AM

# re: Export GridView to Excel Complete Code!
Requesting Gravatar...

error!!!

Control 'GridSales' of type 'GridView' must be placed inside a form tag with runat=server
Left by prie on Jun 07, 2006 3:18 AM

# re: Export GridView to Excel Complete Code!
Requesting Gravatar...
for the form tag error, make sure you include the the last function....if you use VB it is:

Public Overrides Sub VerifyRenderingInServerForm(ByVal control As System.Web.UI.Control)

End Sub
Left by matt filipiak on Jun 19, 2006 12:23 PM

# re: Export GridView to Excel Complete Code!
Requesting Gravatar...
Control 'dnn_ctr370_ViewUtente_GridView1' of type 'GridView' must be placed inside a form tag with runat=server.
Left by Maurizio on Aug 24, 2006 7:39 AM

# re: Export GridView to Excel Complete Code!
Requesting Gravatar...
Thanks for your code, it works great.

Just a question, the text in my gridview is in spanish, and when I export it to excel changes all the accents and ñ with som rare text.

EG: Revisión gives me Revisión

Any suggestions??
Left by Alejandro Color on Aug 24, 2006 5:40 PM

# re: Export GridView to Excel Complete Code!
Requesting Gravatar...
Do anyone has the code in VB?
Left by vb on Sep 01, 2006 1:04 AM

# re: Export GridView to Excel Complete Code!
Requesting Gravatar...
error!!!

Control 'GridSales' of type 'GridView' must be placed inside a form tag with runat=server

please reply at vedcyrus@yahoo.com
Left by chandan on Sep 27, 2006 8:50 PM

# INSIDE USER CONTROL DOESN'T WORK
Requesting Gravatar...
and...yes I include the the last function in the page. Geting Error:
RegisterForEventValidation can only be called during Render();
Left by cesar on Sep 30, 2006 11:07 AM

# re: INSIDE USER CONTROL DOESN'T WORK
Requesting Gravatar...
Add EnableEventValidation = "false" in your page directive will solve the Render() error.
Left by Vincent on Oct 08, 2006 11:15 PM

# re: Export GridView to Excel Complete Code!
Requesting Gravatar...
Hello, I'm trying to do this inside an Atlas' Update Panel... but since Atlas doesn't call a full postback, there is no way to get this export with Response.Write...

Any workarounds?

Thanks in advance.
Left by Yendi on Oct 10, 2006 11:30 PM

# re: Export GridView to Excel Complete Code!
Requesting Gravatar...
Thanks,
I used it on an Intranet application and it is working well. I however put in
try
{

}
Catch(Exception ex)
{

}
Left by Godwin on Oct 20, 2006 7:14 AM

# re: Export GridView to Excel Complete Code!
Requesting Gravatar...
AzamSharp,

Great video and it works fine without UpdatePanel control.

When I put it inside UpdatePanel control, it gives this error:
Sys.WebForms.PageRequestManagerParserErrorException: The message received from teh server could not be parsed. Common causes for this error are when the response is modified by calls to Response.Write(), response filters, HttpModules, or server trace is enabled.
Details: Error parsing near '<div> <table cells'.

But after I set EnablePartialRendering=false for ScriptManager. It works fine.

Any idea?

Many thanks.

David
Left by David on Nov 14, 2006 9:32 AM

# re: Export GridView to Excel Complete Code!
Requesting Gravatar...
I am still getting the missing file error. And it is trying to find my datagrid.css file.

any suggestions?
Left by Mary on Nov 14, 2006 2:49 PM

# re: Export GridView to Excel Complete Code!
Requesting Gravatar...
Fix of Error: Control 'GridView1' of type 'GridView' must be placed inside a form tag with runat=server
Left by RK on Nov 17, 2006 7:59 AM

# re: Export GridView to Excel Complete Code!
Requesting Gravatar...
Fix of Error: Control 'GridView1' of type 'GridView' must be placed inside a form tag with runat=server
http://msdn2.microsoft.com/en-us/library/system.web.ui.page.verifyrenderinginserverform.aspx
Left by RK on Nov 17, 2006 8:01 AM

# re: Export GridView to Excel Complete Code!
Requesting Gravatar...
David..
Can you solve the problem of EnablePartialRendering=false ?
i get the same error message.

Nicolas
Left by Nicolas on Nov 19, 2006 1:03 PM

# re: Export GridView to Excel Complete Code!
Requesting Gravatar...
I have the AJAX EnablePartialRendering problem as well.

Anyone?
Left by Anzel on Dec 06, 2006 1:46 PM

# re: Export GridView to Excel Complete Code!
Requesting Gravatar...
Hi,

Your code working well, but when my customers access from linux based systems, the exported file is opening in openoffice writer instead of openoffice calc. I want to open it in calc. how this problem solved?
Left by Suresh on Dec 07, 2006 7:06 AM

# re: Export GridView to Excel Complete Code!
Requesting Gravatar...
This works pretty well, I am using master pages and got this up and running within minutes. Thanks Azam!!
Left by Matt on Dec 13, 2006 4:57 PM

# re: Export GridView to Excel Complete Code!
Requesting Gravatar...
Azam, thank you for the the tutorial.
Left by Koloa on Dec 15, 2006 6:27 AM

# re: Export GridView to Excel Complete Code!
Requesting Gravatar...
<I tried to export unicode characters, and set Response.Charset = "utf-8", but it is not working.>

just change this part of code:
Response.Write(stringWrite.ToString());

to this:
byte[] converted = System.Text.Encoding.GetEncoding("utf-8").GetBytes(stringWrite.ToString());
Response.BinaryWrite(converted);

Have fun ;)
Left by Airstriker on Dec 29, 2006 4:05 AM

# re: Export GridView to Excel Complete Code!
Requesting Gravatar...
Excellent!
All working just fine!
May I suggest posting a VB version as well... for the lazy ones like me :)
Left by Pp on Feb 01, 2007 3:58 PM

# Can anybody Help...
Requesting Gravatar...
I did the same, but i am getting the following error .

"'C:\Documents and Settings\kmayarovich\Local Settings\Temporary Internet Files\Content.IE5\JUW7BHG5\Repot[1].xls' could not be found. Check the spelling of the file name, and verify that the file location is correct.

If you are trying to open the file from your list of most recently used files on the File menu, make sure that the file has not been renamed, moved, or deleted."
Left by Deeps on Feb 08, 2007 3:21 AM

# re: Export GridView to Excel Complete Code!
Requesting Gravatar...
I like your videos and other examples very much.

Please explain how to set the path where the excel file should be saved in the code behind.

Is there possible to save excel without asking the user and just put the message that file is saved?

Best regards
Left by Leander Šeško on Feb 18, 2007 12:47 AM

# re: Export GridView to Excel Complete Code!
Requesting Gravatar...
the response.end causes the page execution to stop, does anyone know how to avoid this ?
Left by William on Mar 01, 2007 8:47 PM

# re: Export GridView to Excel Complete Code!
Requesting Gravatar...
This is excellent code - thanks, I had this working in only a few moments. Question, anyone know how to export all pages of data if the gridview is set up to do paging (50 records per page)?
Left by Jill on Mar 02, 2007 8:18 AM

# re: Export GridView to Excel Complete Code!
Requesting Gravatar...
Anyone came to know how to export all pages of data if the gridview is set up to do paging (50 records per page)?
Also, if i have hyperlinks in my column, how do i remove that formatting from my excel file?
Left by Pat on Mar 19, 2007 9:54 PM

# re: Export GridView to Excel Complete Code!
Requesting Gravatar...
How to remove the formatting in the resulting excel sheet?
I mean I don't want the color of the Headers.. in the resulting excel sheet

Thanks
Left by Chander on Apr 09, 2007 7:41 PM

# re: Export GridView to Excel Complete Code!
Requesting Gravatar...
HI, thanks for your code.
When i use it though i get this error
RegisterForEventValidation can only be called during Render();

plz give me full code to solve this thanx
Left by vicky on Apr 18, 2007 6:09 AM

# re: Export GridView to Excel Complete Code!
Requesting Gravatar...
Hi

When using the UpdatePanel, I'm still getting the error:
"The message received from the server could not be parsed. Possible causes are calls to Response.Write...etc."
Please help.
Left by Terence on Apr 19, 2007 3:33 AM

# re: Export GridView to Excel Complete Code!
Requesting Gravatar...
I ran into that rendering issue as well - here is the solution I came up with:

http://mattberseth.com/blog/2007/04/export_gridview_to_excel_1.html
Left by Matt Berseth on Apr 25, 2007 7:43 PM

# re: Export GridView to Excel Complete Code!
Requesting Gravatar...
How to I set one of the columns in the exported excel to Number format with 2 decimals and all other columns to text?
Left by Krutika on May 03, 2007 11:25 AM

# re: Export GridView to Excel Complete Code!
Requesting Gravatar...
{"Control 'GridView1' of type 'GridView' must be placed inside a form tag with runat=server."}

i m gettng this error...while running the code above.
Left by Sandip on Jun 18, 2007 3:27 AM

# re: Export GridView to Excel Complete Code!
Requesting Gravatar...
Sys.WebForms.PageRequestManagerParserErrorException: The message received from teh server could not be parsed. Common causes for this error are when the response is modified by calls to Response.Write(), response filters, HttpModules, or server trace is enabled.
Details: Error parsing near '<div> <table cells'.
Left by hamid on Jun 24, 2007 3:41 AM

# re: Export GridView to Excel Complete Code!
Requesting Gravatar...
Working in AJAX is simple. Just wrap the Grid view inside an Update pannel and make sure that the control that updates the Pannel (your export button) is set as a postbacktrigger.
Left by Mooglegiant on Jun 25, 2007 3:35 PM

# re: Export GridView to Excel Complete Code!
Requesting Gravatar...
Hallelujah! Thanks Mooglegiant. That last tip worked like a charm :)
Left by inky on Jul 19, 2007 12:25 PM

# re: Export GridView to Excel Complete Code!
Requesting Gravatar...
I tryed the example and when open the dialog box, i save the file into the desktop and has like a .xls file. However when i open it and i insert a new worsheet to manipulate the file, i click the button save, it saves like a html file (creat a new folder). I have to "save as" to save like excel file. Does everyone knows why it happened?

Thank you!
Left by Kamal Jindal on Jul 31, 2007 12:19 AM

# re: Export GridView to Excel Complete Code!
Requesting Gravatar...
Your code working well, but when my customers access from linux based systems, the exported file is opening in openoffice writer instead of openoffice calc. I want to open it in calc. how this problem solved?
Thank You
Left by Kamal Jindal on Jul 31, 2007 12:26 AM

# re: Export GridView to Excel Complete Code!
Requesting Gravatar...
I using Master page and havinf error say :

RegisterForEventValidation Can only be called during Render();

any help... thanks in advance.
Left by Keith on Aug 08, 2007 12:50 AM

# re: Export GridView to Excel Complete Code!
Requesting Gravatar...
Hello,

Thanks for the code, works fine !

Is it possible to add text in my excel file before the grid data ? For exemple add a title, date and the grid data starts at row4...

Thanks in advance.
Left by tsbob on Aug 08, 2007 6:54 AM

# re: Export GridView to Excel Complete Code!
Requesting Gravatar...
I have a Divtag displayed on page, for look & feel i have display in grid format... actually am binding the grid dynamically in the run time... and adding rows to it using javascript...now I need a export btn to export the data from page pls help me...
Left by swaminathan on Aug 23, 2007 11:29 AM

# re: Export GridView to Excel Complete Code!
Requesting Gravatar...
I am having the exact same problem that Hamid reported earlier - does anyone have a solution for this?

Help is much appreciated.

Sys.WebForms.PageRequestManagerParserErrorException: The message received from teh server could not be parsed. Common causes for this error are when the response is modified by calls to Response.Write(), response filters, HttpModules, or server trace is enabled.
Details: Error parsing near '<div> <table cells'.
Left by Nelson on Aug 30, 2007 3:36 PM

# re: Export GridView to Excel Complete Code!
Requesting Gravatar...
Here is the VB Code. This will solve " Control 'GridSales' of type 'GridView' must be placed inside a form tag with runat=server " problem

Dim stringWrite As IO.StringWriter
Dim htmlWrite As HtmlTextWriter
Dim frm As HtmlForm = New HtmlForm()

Response.Clear()

Response.AddHeader("content-disposition", "attachment;filename=FileName.xls")

Response.Charset = ""

Response.ContentType = "application/vnd.ms-xls"

stringWrite = New IO.StringWriter

htmlWrite = New HtmlTextWriter(stringWrite)

Controls.Add(frm)
frm.Controls.Add(WeldGridView)
frm.RenderControl(htmlWrite)

Response.Write(stringWrite.ToString())

Response.End()
Left by Sunny on Sep 04, 2007 2:35 PM

# re: Export GridView to Excel Complete Code!
Requesting Gravatar...
hai,
I Have tried this and i got the export option to Excel Sheet.
but it has save as option while exporting . I need to Export the Data Grid without Save As option...
Left by Manimozhi.R on Sep 06, 2007 6:35 AM

# re: Export GridView to Excel Complete Code!
Requesting Gravatar...
After reading many articles and comments from many people ( and obviously having the same issue. Using a combination of different peoples suggestions I can confidently say the following

Setting the EnablePartialRendering to false does work however this negates the idea of Ajax, as it stops the asynchronous updates.

The key to the problem lay in what Mooglegiant said.
Set the trigger for the update panel ( the excel button ) to be a postback trigger.
however you need to make sure this button is placed inside the same updatepanel as the gridview, otherwise it won't be a postback trigger.

My thanks goes to mooglegiant for pushing me in the right direction on this.

Sean
Left by Sean Williams on Sep 26, 2007 12:50 AM

# re: Export GridView to Excel Complete Code!
Requesting Gravatar...
Hi! Is there a code which I can just the program not to prompt the user whether they want to save or open?
I want it to just work in the backgroun, auto-save for the user.
Can this be done?
Left by mizuki on Sep 28, 2007 4:48 AM

# re: Export GridView to Excel Complete Code!
Requesting Gravatar...
1. turn off paging and sorting for the grid
2. add this code to your page:

public override void VerifyRenderingInServerForm(Control control)
{

}

3. And in your aspx page set EnableEventValidation="false"

After doing those 3 things, i got it working.
Left by howdy on Oct 16, 2007 7:18 PM

# re: Export GridView to Excel Complete Code!
Requesting Gravatar...
The code works fine in a standard website project. However, when I use it in a Web App Project, it exports the entire web page, buttons and all, rather than just the gridview. Any thoughts on a solution?
Left by SteveT on Oct 17, 2007 3:00 AM

# re: Export GridView to Excel Complete Code!
Requesting Gravatar...
"Control 'GridView1' of type 'GridView' must be placed inside a form tag with runat=server. " im getting above error
Left by udaya on Oct 28, 2007 5:15 PM

# re: Export GridView to Excel Complete Code!
Requesting Gravatar...
hai,
I Have tried this and i got the export option to Excel Sheet.
but it has save as option while exporting . I need to Export the Data Grid without Save As option...

Left by Sandhya on Nov 04, 2007 11:58 PM

# re: Export GridView to Excel Complete Code!
Requesting Gravatar...
Hi everyone...

An easy solution to get past the, "RegisterForEventValidation Can only be called during Render();" error message is to add a boolean value to your page and set it to false on the page init. Then wire up your export button to set that export boolean to true. Then on the pre-render of the Gridview just add the export to excel code snippet and set it to run only when the export boolean is set to true. Works like a charm.

Left by Steven S on Nov 13, 2007 4:57 AM

# re: Export GridView to Excel Complete Code!
Requesting Gravatar...
"Control 'GridView1' of type 'GridView' must be placed inside a form tag with runat=server. " im getting above error

Left by Pranjit Kalita on Nov 22, 2007 8:37 PM

# re: Export GridView to Excel Complete Code!
Requesting Gravatar...
Hi All:
I am using this solution. This is working great.
I have one problem. The file is exported great - I checked the file size and then open the exported file. I did a minor change into excel and then save. The file size is different.

Any suggestio, why this is happening.
Left by David on Nov 27, 2007 8:47 PM

# re: Export GridView to Excel Complete Code!
Requesting Gravatar...
{"Control 'GridView1' of type 'GridView' must be placed inside a form tag with runat=server."}

i m gettng this error...Can somebody send me the code to resolve this issue
Left by Bab on Nov 28, 2007 6:15 AM

# re: Export GridView to Excel Complete Code!
Requesting Gravatar...
1. turn off paging and sorting for the grid
2. add this code to your page:

public override void VerifyRenderingInServerForm(Control control)
{

}
add these this i got it working
Left by nitin jain on Nov 30, 2007 7:22 PM

# re: Export GridView to Excel Complete Code!
Requesting Gravatar...
2 howdy
Great thanks dude - all work good )
Left by Esk on Nov 30, 2007 11:54 PM

# re: Export GridView to Excel Complete Code!
Requesting Gravatar...
hai,
I Have tried this and i got the export option to Excel Sheet.
but it has save as option while exporting . I need to Export the Data Grid without Save As option...
Left by hugo oyunları on Dec 03, 2007 5:37 AM

# re: Export GridView to Excel Complete Code!
Requesting Gravatar...
Try http://www.gridviewtoexcel.com
Left by Ettore on Dec 04, 2007 11:58 PM

# re: Export GridView to Excel Complete Code!
Requesting Gravatar...
Hi, its great.
Actually i used crystal treport to export data in Excel.
But this code help me to directly export in Excel.
Thanks Once Again.
Anant Patil
Left by Anant Patil on Dec 05, 2007 5:28 PM

# re: Export GridView to Excel Complete Code!
Requesting Gravatar...
Control 'GridView1' of type 'GridView' must be placed inside a form tag with runat=server.
Left by Aniesh Cherian on Dec 06, 2007 7:08 PM

# re: Export GridView to Excel Complete Code!
Requesting Gravatar...
.

I feel the error of the c# code is given below
/this.GridView1.Page.EnableViewState = false;
// StringWriter tw = new StringWriter();
// HtmlTextWriter hw = new HtmlTextWriter(tw);
// this.GridView1.RenderControl(hw); GridView1.RenderControl(hw);

// string HtmlInfo = tw.ToString().Trim();

// string DocFileName = "file1" + ".xls";
// string FilePathName = Request.PhysicalPath;
// FilePathName = FilePathName.Substring(0, FilePathName.LastIndexOf("\\"));

// FilePathName = FilePathName + "\\" + DocFileName;
// File.Delete(FilePathName);
// FileStream Fs = new FileStream(FilePathName, FileMode.Create);
// BinaryWriter BWriter = new BinaryWriter(Fs,System.Text.Encoding.GetEncoding("UTF-8"));
//BWriter.Write(HtmlInfo);
// BWriter.Close();
// Fs.Close();

Control 'GridView1' of type 'GridView' must be placed inside a form tag with runat=server
Left by Aniesh Cherian on Dec 06, 2007 7:09 PM

# re: Export GridView to Excel Complete Code!
Requesting Gravatar...
"RegisterForEventValidation can only be called during Render();"

Set Paging property of the gridview to false and it will work.

btw many thanks for this code it helped me very much

Though I had to convert it all to VB.net 1st on my own :D
Left by Anurag on Dec 06, 2007 8:53 PM

# re: Export GridView to Excel Complete Code!
Requesting Gravatar...
hi ,
thank for this post.... but i am having some problem while using this in update panel its firing somee exceptions .... any solution for this........
Left by Naga Mohan Kumar P on Dec 22, 2007 5:07 PM

# re: Export GridView to Excel Complete Code!
Requesting Gravatar...
Found these on a SharePoint blog.&nbsp; There appears to be lots of useful web parts here as well as
Left by hugo oyunlari on Dec 26, 2007 10:55 AM

# re: Export GridView to Excel Complete Code!
Requesting Gravatar...
Is it possible to export a Grid View to Excel and turn on the "Filter" option in Excel? If so, please provide the code.
Left by David Mayer on Jan 08, 2008 7:16 AM

# re: Export GridView to Excel Complete Code!
Requesting Gravatar...
I have a case...
I want to export data like '00234'
in excel the data changes to '234'
I want the zero still view at excel..., i mean at excel the data still view like '00234'
what must i do....
help plz....
thanks before.....
Left by Elny on Jan 08, 2008 4:42 PM

# re: Export GridView to Excel Complete Code!
Requesting Gravatar...
Left by Elny at 1/8/2008 4:42 PM

I have same problem like ELny, Elny have you found any solution of it?
Left by jignesh on Jan 30, 2008 7:07 PM

# re: Export GridView to Excel Complete Code!
Requesting Gravatar...
You little ripper!
Thanks heaps for the example, and the continued support with the various errors... A great help for a newbie!
Left by Shane on Feb 02, 2008 11:45 PM

# re: Export GridView to Excel Complete Code!
Requesting Gravatar...
Free opensource code that exports a gridview to excel with Zero code. Check http://www.codeplex.com/ExportToExcel
Left by RK on Feb 07, 2008 2:23 AM

# re: Export GridView to Excel Complete Code!
Requesting Gravatar...
try this.
http://forums.asp.net/p/1043486/1458325.aspx#1458325
Left by Hariharasudhan C on Feb 07, 2008 4:35 AM

# re: Export GridView to Excel Complete Code!
Requesting Gravatar...
Control 'GridView1' of type 'GridView' must be placed inside a form tag with runat=server

for this you can use this....

GridView1.Attributes["runat"] = "server";

this is working fine
Left by Mukesh Kumar Singh on Feb 07, 2008 6:44 PM

# re: Export GridView to Excel Complete Code!
Requesting Gravatar...
Hi it was very nice....i learnt a new thing ....keep continue
Left by Siva Reddy on Feb 12, 2008 7:20 PM

# re: Export GridView to Excel Complete Code!
Requesting Gravatar...
////////export data in to textfile ///////////



String strDestinationFile;
strDestinationFile = "C:\\Report.txt";
TextWriter tw = new StreamWriter(strDestinationFile);
//writing the header

tw.Write("Master Capital Services Limited".PadLeft(50));
tw.WriteLine();
tw.Write("Holding Summary: From:31/03/2008 Trades Upto:31/03/2008 Transactions Upto:31/03/2008");
tw.WriteLine();
tw.Write("Page No:1 Date:15/02/2008".PadLeft(40));
tw.WriteLine();
tw.Write("------------------------------------------------------------------------------------");
tw.WriteLine();
tw.Write(GridView1.Columns[0].HeaderText.PadRight(15));
tw.Write(GridView1.Columns[1].HeaderText.PadRight(17));
tw.Write(GridView1.Columns[2].HeaderText.PadRight(27));
tw.Write(GridView1.Columns[3].HeaderText.PadRight(15));
tw.Write(GridView1.Columns[4].HeaderText.PadRight(15));
tw.WriteLine();
tw.Write("-------------------------------------------------------------------------------------");
tw.WriteLine();


//writing the data
for (int x = 0; x < GridView1.Rows.Count; x++)
{

tw.Write("-------------------------------------------------------------------------------------");
tw.WriteLine();
tw.Write(GridView1.Rows[x].Cells[0].Text.PadRight(15));
tw.Write(GridView1.Rows[x].Cells[1].Text.PadRight(17));
tw.Write(GridView1.Rows[x].Cells[2].Text.PadRight(27));
tw.Write(GridView1.Rows[x].Cells[3].Text.PadLeft(10));
tw.Write(GridView1.Rows[x].Cells[4].Text.PadLeft(10));
tw.WriteLine();


}
tw.Close();

}
Left by Ankush sarna on Feb 18, 2008 1:01 AM

# re: Export GridView to Excel Complete Code!
Requesting Gravatar...
plz give me a complete code in vb.net
Left by ram on Feb 18, 2008 10:03 PM

# re: Export GridView to Excel Complete Code!
Requesting Gravatar...
Hi,
thanks to all. ur comments helped me a lot. while exporting to excel file save option works fine but when we open no data is visible.
Plz help me on this
Left by Praveen Paluri on Feb 19, 2008 9:02 PM

# re: Export GridView to Excel Complete Code!
Requesting Gravatar...
Hi I am getting the follwing error even i used this code.

can anybody help me ?

Control 'ctl00_ContentPlaceHolder1_grdIRR' of type 'GridView' must be placed inside a form tag with runat=server
Left by Mahesh on Feb 24, 2008 7:04 PM

# re: Export GridView to Excel Complete Code!
Requesting Gravatar...
Thanks! Solution works great!

All answers to questions were found in the posts too. Appreciate the work everyone.
Left by Ben on Feb 26, 2008 9:00 AM

# re: Export GridView to Excel Complete Code!
Requesting Gravatar...
Hi,

Thanks for the above code.

I found one simple trick. If you do not want to get the colors and fonts in the excel sheet, just create a temporary GridView object and remove the formatting in that object. This also solves the problem of the control being in another control.

Say,

dim tempGV as GridView = Me.GridView1

'Change the fonts, colors, header styles
'etc

If anyone has better idea, please share it.
Left by Noorul Ahmed on Mar 04, 2008 7:40 PM

# Working code - Tested
Requesting Gravatar...
Response.Clear();
Response.AddHeader("content-disposition", "attachment;filename=Report.xls");
Response.ContentType = "application/excel";
System.IO.StringWriter buffer = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter writer = new HtmlTextWriter(buffer);
writer.WriteLine("<table cellspacing=\"0\", rules=\"all\", border=\"1\">");
writer.WriteLine("<tr><td colspan=\"8\">Executive Escalation Report</td></tr>");
ReportGridView.HeaderRow.RenderControl(writer);
foreach (GridViewRow row in ReportGridView.Rows)
row.RenderControl(writer);
writer.WriteLine("</table>");
Response.Write(buffer.ToString());
MemoryStream ms = new MemoryStream();
StreamWriter sr = new StreamWriter(ms);
sr.WriteLine(buffer.ToString());
sr.Flush();
ms.Position = 0;
Left by Sunsurej on Mar 06, 2008 1:02 AM

# re: Export GridView to Excel Complete Code!
Requesting Gravatar...
Hello,Thanks For this code.
Its very Useful for me.
But from this code export girdview with its original formate but i want to export content of girdview in excel formate.
Left by Kruti on Apr 03, 2008 6:58 PM

# re: Export GridView to Excel Complete Code!
Requesting Gravatar...
I know this seems terribly simple for a workaround, but it DOES work and the Datagrid does render...The key is to catch the HTTPException.

StringBuilder SB = new StringBuilder();
StringWriter SW3 = new StringWriter(SB);
HtmlTextWriter htmlTW = new HtmlTextWriter(SW);
try
{
GridView1.RenderControl(htmlTW);
}
catch (HttpException)
{

}
Left by SimpleMan on Apr 23, 2008 9:07 AM

# re: Export GridView to Excel Complete Code!
Requesting Gravatar...
hey ur code is great .....
i have a problem ..if i enable paging it gives an exception pageindexchanging not handled while switching to the next page....how do i tackle this problem??
Left by rohan on May 12, 2008 12:59 AM

# re: Export GridView to Excel Complete Code!
Requesting Gravatar...
Here is the complete code to Export GridView to Excel:
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;

public partial class ExportGridView : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
GridView1.DataSource = BindData();
GridView1.DataBind();
}
}



private string ConnectionString
{

get { return @"Server=localhost;Database=Northwind;
Trusted_Connection=true"; }

}



private DataSet BindData()
{
// make the query
string query = "SELECT * FROM Categories";
SqlConnection myConnection = new SqlConnection(ConnectionString);
SqlDataAdapter ad = new SqlDataAdapter(query, myConnection);
DataSet ds = new DataSet();
ad.Fill(ds, "Categories");
return ds;

}




protected void Button1_Click(object sender, EventArgs e)
{
Response.Clear();

Response.AddHeader("content-disposition", "attachment;
filename=FileName.xls");

Response.Charset = "";

// If you want the option to open the Excel file without saving than

// comment out the line below

// Response.Cache.SetCacheability(HttpCacheability.NoCache);

Response.ContentType = "application/vnd.xls";

System.IO.StringWriter stringWrite = new System.IO.StringWriter();

System.Web.UI.HtmlTextWriter htmlWrite =
new HtmlTextWriter(stringWrite);

GridView1.RenderControl(htmlWrite);

Response.Write(stringWrite.ToString());

Response.End();

}

public override void VerifyRenderingInServerForm(Control control)
{

}
}


Left by sasikanth on May 26, 2008 6:32 PM

# re: Export GridView to Excel Complete Code!
Requesting Gravatar...
this code perfectly for exporting values to excel sheet from gridview
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;

public partial class ExportGridView : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
GridView1.DataSource = BindData();
GridView1.DataBind();
}
}



private string ConnectionString
{

get { return @"Server=localhost;Database=Northwind;
Trusted_Connection=true"; }

}



private DataSet BindData()
{
// make the query
string query = "SELECT * FROM Categories";
SqlConnection myConnection = new SqlConnection(ConnectionString);
SqlDataAdapter ad = new SqlDataAdapter(query, myConnection);
DataSet ds = new DataSet();
ad.Fill(ds, "Categories");
return ds;

}




protected void Button1_Click(object sender, EventArgs e)
{
Response.Clear();

Response.AddHeader("content-disposition", "attachment;
filename=FileName.xls");

Response.Charset = "";

// If you want the option to open the Excel file without saving than

// comment out the line below

// Response.Cache.SetCacheability(HttpCacheability.NoCache);

Response.ContentType = "application/vnd.xls";

System.IO.StringWriter stringWrite = new System.IO.StringWriter();

System.Web.UI.HtmlTextWriter htmlWrite =
new HtmlTextWriter(stringWrite);

GridView1.RenderControl(htmlWrite);

Response.Write(stringWrite.ToString());

Response.End();

}

public override void VerifyRenderingInServerForm(Control control)
{

}
}


Left by sasikanth on May 26, 2008 6:32 PM

# re: Export GridView to Excel Complete Code!
Requesting Gravatar...
How to make the excel sheet to read only.that is no one can edit that excel file.can any one help me please
Left by Agnes Loyola on Jun 09, 2008 1:07 AM

# re: Export GridView to Excel Complete Code!
Requesting Gravatar...
i used the same code to export the gridview to excel but the problem i faced was the contents in the gridview doesnot autofit in excel sheet.
Left by rathiagu on Jun 09, 2008 6:17 AM

# re: Export GridView to Excel Complete Code!
Requesting Gravatar...
i am exportng dataset to excel on the click of button i got an error msg that "'C:\Documents and Settings\Local Settings\Temporary Internet Files\Content.IE5\JUW7BHG5\Repot[1].xls' could not be found. Check the spelling of the file name, and verify that the file location is correct.

If you are trying to open the file from your list of most recently used files on the File menu, make sure that the file has not been renamed, moved, or deleted." can u plz help me to solve this error......
Left by mugdha on Jun 10, 2008 6:57 PM

# re: Export GridView to Excel Complete Code!
Requesting Gravatar...
can i get the vb code?
Left by bard on Jun 17, 2008 1:57 PM

# re: Export GridView to Excel Complete Code!
Requesting Gravatar...
Hi i have an existing excel template and data from the grid view has to bind in particular rows in a sheet in tat template as it has many sheets. so please give code or share ur knowledge in helping me out...

plz give solution 2 my email address vijaikanth86@gmail.com .Thanks:)
Left by vijai on Aug 26, 2010 11:19 PM

# re: Export GridView to Excel Complete Code!
Requesting Gravatar...
I want to export from datagrid into an excel, then do some formatting like freeze panes, filter, grouping to some of the column/row. How could this be done? Now I can export everything to the excel except for the features above.. :(.
Left by Handsome Lee on Oct 19, 2010 10:13 PM

# re: Export GridView to Excel Complete Code!
Requesting Gravatar...
When I applied the same code. An exception was thrown (
Control 'grv1' of type 'GridView' must be placed inside a form tag with runat=server.)
Ma gridView is already inside form
Left by Harish on Oct 26, 2010 7:26 PM

# re: Export GridView to Excel Complete Code!
Requesting Gravatar...
Hi i have an existing excel template and data from the grid view has to bind in particular rows in a sheet in tat template as it has many sheets. so please give code or share ur knowledge in helping me out...

plz give solution 2 my email address amarendar_1@yahoo.com .Thanks:)
Left by amar on Nov 22, 2010 5:45 PM

Your comment:
 (will show your gravatar)


Copyright © Mohammad Azam | Powered by: GeeksWithBlogs.net | Join free