|
|
Extensive Study of GridView Export to Excel
AzamSharp
Published Date: 8/13/2006 1:53:53 PM
Views: 88396
Abstract:
Exporting GridView to Excel is a very common task which is performed in most of the web applications. There are various techniques of exporting the GridView to excel and it highly depends on the application scenario. In this article I will demonstrate some techniques that you will find useful.
Introduction:
Exporting GridView to Excel is a very common task which is performed in most of the web applications. There are various techniques of exporting the GridView to excel and it highly depends on the application scenario. In this article I will demonstrate some techniques that you will find useful.
GridView Export the Excel (Basic Code):
Let's start with the basic export scenario. First, we need to populate the GridView with some data. I have created a custom table which has number of fields. You can check out the screen shot below.

Now, the next task is to populate the GridView with the data from the database. Check out the following code which uses the DataSet to populate the GridView.
| private void BindData()
{
SqlConnection myConnection = new SqlConnection("Server=localhost;Database=School;Trusted_Connection=true");
SqlDataAdapter ad = new SqlDataAdapter("SELECT * FROM Users", myConnection);
DataSet ds = new DataSet();
ad.Fill(ds);
gvUsers.DataSource = ds;
gvUsers.DataBind();
} |

So, now the GridView is populated with the data. The next task is to export the GridView to excel. You can use the following code for the button click event.
| Response.ClearContent();
Response.AddHeader("content-disposition", "attachment; filename=MyExcelFile.xls");
Response.ContentType = "application/excel";
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
gvUsers.RenderControl(htw);
Response.Write(sw.ToString());
Response.End(); |
You will also need to override the VerifyRenderingInServerForm method. Take a look at the code below:
| public override void VerifyRenderingInServerForm(Control control)
{
} |
When you click the Export to Excel (Default) button a dialog box will popup which will allow you to open or save the exported file. Select open the file and you will see the exported data in the excel spreadsheet. Take a look at the screen shot below which shows the exported GridView in excel spreadsheet.

Exporting GridView to Excel With Style:
Did you see the problem in the above exportation code? Yes, the leading zero's were truncated. It means that if your ID was 000345 it will show up as 345. You can fix this problem by adding a CSS script to the output stream. In order for the ID column to appear correctly you need to store it as text. The text format in excel is represented by "mso-number-format:"\@". Once, you know the format you can append the style in the output stream. Check out the code below.
| protected void Btn_ExportClick(object sender, EventArgs e)
{
string style = @"<style> .text { mso-number-format:\@; } </style> ";
Response.ClearContent();
Response.AddHeader("content-disposition", "attachment; filename=MyExcelFile.xls");
Response.ContentType = "application/excel";
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
gvUsers.RenderControl(htw);
// Style is added dynamically
Response.Write(style);
Response.Write(sw.ToString());
Response.End();
}
public override void VerifyRenderingInServerForm(Control control)
{
} |
As, you can see in the above code that I have used the string variable "style" to hold the style of the GridView column. And I used the Response.Write method to write the style to the output stream. The last thing that you need to do is to add the style to the ID column. This can be done in the RowDataBound event of the GridView control.
| protected void gvUsers_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.Cells[1].Attributes.Add("class", "text");
}
} |
Now, when you export the GridView to excel your exported file will look something like this.

|
Finding Style For the Column
You can easily find the correct style for your GridView column by opening the exported excel file. Now, click on the column header and select "Format Cells". This will present you with several options to format the cells. Select text from the list and save the file as .htm (webpage) file. Now, open the webpage in your browser and view the source. In the style section you will find different styles for the table cell (td element). Now, locate the ID column by doing a search on the source of the webpage. You will find a line like this: <td class=xl27 width=35 style='border-left:none;width:26pt'>ID</td> As, you can see that the above table cell uses the class x127. Now, go to the styles section and find the x127. .xl27 {mso-style-parent:style0; font-weight:700; mso-number-format:"\@"; text-align:center; vertical-align:middle; border:.5pt solid black; white-space:normal;} When you look up the .x127 you will find the format of the cell defined as mso-number-format:"\@";. |
Exporting GridView With LinkButtons and Paging:
When you try to export the GridView which contains LinkButtons and Paging enabled then you might see the following error.

You can easily handle this error by going to the page source and turning the EnableEventValidation = "false".
| <%@ Page Language="C#" EnableEventValidation="false" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %> |
But let's take a look at the exported file.

As, you can see that the LinkButtons and DropDownLists are also exported with the GridView control. Although the DropDownList does display the correct user selections but it does not look good in the exported file. So, let's see how we can remove the DropDownList and only display the selected text.
I have created a simple DisableControls method which iterates through the GridView control and replace all LinkButtons and DropDownLists with the Literal control.
| private void DisableControls(Control gv)
{
LinkButton lb = new LinkButton();
Literal l = new Literal();
string name = String.Empty;
for (int i = 0; i < gv.Controls.Count; i++)
{
if (gv.Controls[i].GetType() == typeof(LinkButton))
{
l.Text = (gv.Controls[i] as LinkButton).Text;
gv.Controls.Remove(gv.Controls[i]);
gv.Controls.AddAt(i, l);
}
else if (gv.Controls[i].GetType() == typeof(DropDownList))
{
l.Text = (gv.Controls[i] as DropDownList).SelectedItem.Text;
gv.Controls.Remove(gv.Controls[i]);
gv.Controls.AddAt(i, l);
}
if (gv.Controls[i].HasControls())
{
DisableControls(gv.Controls[i]);
}
}
} |
The idea is very simple just replace all the LinkButton and DropDownList controls with a Literal control and assign their selection to the Literal control Text property. You need to call this function before the exportation takes place.
| protected void Btn_ExportExcelPaging(object sender, EventArgs e)
{
DisableControls(gvUsers);
Response.ClearContent();
Response.AddHeader("content-disposition", "attachment; filename=MyExcelFile.xls");
Response.ContentType = "application/excel";
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
gvUsers.RenderControl(htw);
Response.Write(sw.ToString());
Response.End();
} |
Now, when you export the GridView you will only see the selected text. Check out the screen shot below which shows the effect.

Conclusion:
In this article you learned different ways to export the GridView to excel. I have attached the complete source code to download. I hope you liked this article, happy coding!
Enter Comment/Feedback
Comments/Feedbacks
|
|
|
|
Subject: GridView Export to Excel, Visual Basic Version?
Name: Arif Ali
Date: 1/30/2007 10:10:51 AM
Comment: I tried to convert this to VB and am getting stuck on the prerendering; i.e., the conversion of checkbox fields, etc. Can you provide a VB version?
Thanks, |
|
|
|
|
|
Subject: How to get Excel in multiple spread sheets
Name: Deepak
Date: 2/16/2007 2:00:12 AM
Comment: Hi ,
The article is superb and is working fine, but i face a problem in exporting large data. My requirement is when the data exeeds max rows of excel (65000) the rest of the data should go to a separate sheet in the same excel file.
Please help me in this regard. Kindly mail me to mace_deepak@yahoo.com. Its very urgent for me... |
|
|
|
|
|
Subject: Re: Exporting Large Data
Name: AzamSharp
Date: 2/17/2007 8:45:50 PM
Comment: Deepak, you might need to use the Office Libraries in order to export the data into different sheets. I think you can make reference to those libraries using the COM reference. |
|
|
|
|
|
Subject: Still not keeping zeros
Name: Ron
Date: 2/20/2007 10:32:27 AM
Comment: Here is my code. I still am missing leading zeros. Can you please help? Thank you in advance.
protected void btnExcel_Click(object sender, EventArgs e)
{
string style = @" ";
gvPartsByVS.DataSource = Session["Parts"];
gvPartsByVS.DataBind();
gvPartsByVS.Font.Size = 8;
gvPartsByVS.Columns[3].ItemStyle.HorizontalAlign = HorizontalAlign.Left;
Response.ClearContent();
Response.AddHeader("content-disposition", "attachment; filename=MyExcelFile.xls");
Response.ContentType = "application/excel";
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
gvPartsByVS.RenderControl(htw);
Response.Write(style);
Response.Write(sw.ToString());
Response.End();
}
public override void VerifyRenderingInServerForm(Control control)
{
}
protected void btnGoBack_Click(object sender, EventArgs e)
{
Response.Redirect("SelectVS.aspx");
}
protected void gvPartsByVS_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.Cells[3].Attributes.Add("class", "text");
}
} |
|
|
|
|
|
Subject: Well Done Keep the GOdd Things Going on
Name: Kamran Bhatti
Date: 3/1/2007 4:26:15 AM
Comment: Great Article Very Well,and thanks |
|
|
|
|
|
Subject: Excellent article
Name: Naga Raja Sharma
Date: 3/1/2007 2:19:44 PM
Comment: This is the best article on excel exporting. The problems discussed are most common and the solution given is is great. Keep up the good work..... |
|
|
|
|
|
Subject: error when used with ATLAS
Name: paul
Date: 3/7/2007 5:31:12 PM
Comment:
Hi,
I used this example and it all worked fine until I added a HoverMenu Control into the gridview, I now get the error pasted below.
any ideas??
Extender control 'hme3' is not a registered extender control. Extender controls must be registered using RegisterExtenderControl() before calling RegisterScriptDescriptors().
Parameter name: extenderControl
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.ArgumentException: Extender control 'hme3' is not a registered extender control. Extender controls must be registered using RegisterExtenderControl() before calling RegisterScriptDescriptors().
Parameter name: extenderControl
Source Error:
Line 44: HtmlTextWriter htw = new HtmlTextWriter(sw);
Line 45:
Line 46: GridView1.RenderControl(htw);
Line 47:
Line 48: Response.Write(sw.ToString());
|
|
|
|
|
|
Subject: error when used with ATLAS
Name: AzamSharp
Date: 3/12/2007 8:46:01 PM
Comment: Hi,
Try using the control outside the GridView. It may be because of the settings of the extender control like using the script manager.
|
|
|
|
|
|
Subject: Good Stuff
Name: linn
Date: 3/27/2007 5:53:35 PM
Comment: Thanks for the very clear illustration of the whole exporting logic, especially the part on error handling. I got everything to work in just 5 mins! :o) |
|
|
|
|
|
Subject: Links for sorting columns remain
Name: JD
Date: 4/5/2007 3:02:53 PM
Comment: Great help, the part on disabling controls really cleaned up the spreadsheet. One question though, the links created in the header cells when sorting is enabled in the gridview remain after calling DisableControls? I had solved this issue previously by setting the AllowSorting property of the gridview to false and rebinding before rendering it to the HtmlTextWriter. Wanting to remove unnecessary code and thinking DisableControls would take care of the headers as well, I was surprised to see the links persist in the spreadsheet.
I know I can just implement my previous code but was wondering if you had an explanation for this, would testing for a data type in addition to LinkButton make DisableControls into the catchall solution? |
|
|
|
|
|
Subject: Good Stuff
Name: Sam
Date: 4/13/2007 7:56:24 AM
Comment: Worked like a charm. Thanks! |
|
|
|
|
|
Subject: export more than one GridView to the same excel workbook but seperate worksheets
Name: eric francois
Date: 4/17/2007 11:29:43 AM
Comment: need to know possibilities for exporting say 3 GridViews on one .aspx page into one excel workbook but each GridView is placed on its own worksheet inside that workbook. So, final result is one workbook (.xls) with 3 worksheet inside of it.
any suggestion will be greatly appreciated! |
|
|
|
|
|
Subject: GridView Export to Excel, using themes
Name: Jean-Luc ROBERT
Date: 4/27/2007 2:13:12 AM
Comment: Great article AzamSharp.
To keep the colors and other format, i use a theme on my gridview, it works great, no need to have css style attributes anymore.
The only issue : with a in my gridview theme, the entire line has the back color in Excel and not only the columns with data.
Any ideas to solve that ? |
|
|
|
|
|
Subject: GridView Export to Excel, using themes
Name: Jean-Luc ROBERT
Date: 4/27/2007 8:40:15 AM
Comment: My solution to remove HeaderStyle BackColor:
System.Drawing.Color headerBackColor = _gridView.HeaderStyle.BackColor;
_gridView.HeaderStyle.BackColor = System.Drawing.Color.Empty;
for (int i = 0; i < _gridView.HeaderRow.Cells.Count; i++)
{
_gridView.HeaderRow.Cells[i].BackColor = headerBackColor;
} |
|
|
|
|
|
Subject: Gridview Export to Excel, Loading notifier
Name: Jean-Luc ROBERT
Date: 4/30/2007 2:20:26 AM
Comment: Does anyone has an idea about a loading notifier ?
Whith a large amount of data, the rendering to an xls flow can be slow, i would like to have a waiting message.
Problem : how to notify when finished ? Javascript can't be used with xls content-type. |
|
|
|
|
|
Subject: Export Large amount of data in separate sheets
Name: Jean-Luc ROBERT
Date: 4/30/2007 6:52:14 AM
Comment: This is a very interisting article:
http://www.codeproject.com/dotnet/ExportToExcel.asp |
|
|
|
|
|
Subject: How to avoid to override VerifyRenderingInServerForm
Name: Jean-Luc ROBERT
Date: 5/2/2007 1:08:45 AM
Comment: The idea : include the gridview in a form.
To avoid a blank line, remove the hidden fields in the resulting code in the div mark out.
The code in c-sharp:
HtmlForm frm = new HtmlForm();
_gridView.Parent.Controls.Add(frm);
frm.Attributes["runat"] = "server";
frm.Controls.Add(_gridView);
frm.RenderControl(htmlWrite);
string htmlResult = stringWrite.ToString();
int iStart = htmlResult.IndexOf(" ") + 5;
_response.Write(htmlResult.Remove(iStart, htmlResult.IndexOf(" ") - iStart));
|
|
|
|
|
|
Subject: How to avoid to override VerifyRenderingInServerForm
Name: Matt Berseth
Date: 5/2/2007 5:40:45 PM
Comment: I ran into this issue too and didn't want to override this method in all of my pages. Here (http://mattberseth.com/blog/2007/04/export_gridview_to_excel_1.html) is the solution I am using. |
|
|
|
|
|
Subject: Decimal in exported Excel
Name: Krutika
Date: 5/3/2007 7:37:56 AM
Comment: I'm trying to export Dataset to Excel spreadsheet.
How to enforce 2 decimal places in excel sheets? |
|
|
|
|
|
Subject: SUPERB!!!!!!!!!!!!!
Name: Whats in a name
Date: 6/5/2007 1:13:21 AM
Comment: Hey Griddy Guy,
You are simply too good man.. A coding genius and the best "TEACHER" i have ever come across.. You make things so "SIMPLE".. Tremendous work.. I Hope you start a site ASPDOTNETGUY.com.. :) will be the end of all my coding problems..
Cheers
True Fan |
|
|
|
|
|
Subject: RE: True Fan
Name: AzamSharp
Date: 6/5/2007 10:10:08 AM
Comment: Hi True Fan,
I am glad you liked the articles and I am very happy that it helped you in development needs. I also have a video website www.videos.gridviewguy.com where I host tutorial videos. I am sure you will find them informative.
PS: The website GridViewGuy is also k nown as TheDotNetGuy.com :)
Thanks,
Azam |
|
|
|
|
|
Subject: Unable to delclare dataset
Name: Steve
Date: 6/11/2007 4:07:56 PM
Comment: Hi-
I'm a novice- I can't seem to get it to declare a dataset. I'm using Vis. Studio 2005 with VB net. Is the dataset option no longer supported? |
|
|
|
|
|
Subject: more than 65000 rows
Name: PRam
Date: 6/12/2007 12:20:25 PM
Comment: Hi Azam
It is working perfectly, but morethan 65k rows, how do i handle?
Help me please
thanks
Prabu
|
|
|
|
|
|
Subject: RE: More than 65K rows
Name: AzamSharp
Date: 6/12/2007 2:05:07 PM
Comment: Hi,
What happens when you try to export more than 65K rows?
Thanks,
|
|
|
|
|
|
Subject: Morethan 65k rows issue
Name: Prabu
Date: 6/13/2007 6:13:05 AM
Comment: Azam,
Morethan 65k rows, have been saved in the excel, but issues is that excel file can not be opend, it throws error. I am expecting solution like that file goes up to 65k 1 file and another 65k another file like that....is it possible.
thanks
Prabu |
|
|
|
|
|
Subject: RE: More than 65K rows
Name: AzamSharp
Date: 6/13/2007 9:40:43 AM
Comment: Hi,
What is the exact error being thrown?
|
|
|
|
|
|
Subject: Seperate Worksheets
Name: Armen
Date: 6/19/2007 12:26:00 PM
Comment: Hi, I've come across your comments many times today in my search for an answer. Thus, I've decided to post a comment.
My dilemma is I have an ASP.NET page with two gridviews. I would like to export both gridviews to an excel workbook, but have each gridview on its own sheet in the excel document.
I have tried many variations of search patterns, yet have not come across any solid answers. |
|
|
|
|
|
Subject: Exporting Large Data
Name: AzamSharp
Date: 6/21/2007 8:57:04 AM
Comment: Hi,
If your application is failing while sending large data then you can put this line in the web.config file.
This increases the request length. |
|
|
|
|
|
Subject: Exporting selected columns to excel
Name: samardeep
Date: 6/24/2007 3:35:38 PM
Comment: hi..
I have made a 100% running export Usercontrol which works fine with any type of control in it..but i want to remove those columns which contains any control within them..and that is too without looping throughout the grid view..pls tell me how can i do it..? |
|
|
|
|
|
Subject: An excellent job by GRIDVIEW GUY...
Name: Srikanth
Date: 6/28/2007 12:33:07 AM
Comment: Hi Grid view guy..
its really very help full post from you..my biggest problem was resolved with this..
but at the same time another problem came up with this..
Paging should be enable in my grid view..but not in excel..
hope you got my point..what i exactly need is I want to export all the data irrespective of paging..
your great full help is required for me now..plz help..
Thank you. |
|
|
|
|
|
Subject: RE: Exporting GridView Paging Issues
Name: AzamSharp
Date: 6/28/2007 3:28:28 PM
Comment: Hi,
If you want the Export file to NOT have paging then simply turn off the page, bind the Gridview and export the gridview. When the export is completed, simply allow the paging again. |
|
|
|
|
|
Subject: No Error but not Exporting data
Name: mima
Date: 6/29/2007 5:54:18 AM
Comment: Hi,
I used above code to export the data from the gridview (code behind is vb.net) not there is not error but no data is exported but only tag like on first cell and on 3rd cell....
Can any body tell me the cause of it..
Thanks in advance |
|
|
|
|
|
Subject: exporting gridview to multiple spread sheet
Name: Priya
Date: 7/20/2007 7:53:58 AM
Comment: Hi,
This is an excellent tutorial.
But do you have any c sharp code on exporting many gridviews in to multi spread sheets. I am using office libraries making reference to COM. I was using the code on VB but for reason am not able to translate to CSHARP. If you alread have the code can you please post it. |
|
|
|
|
|
Subject: Post to multiple spreadsheets and lock spreadsheet
Name: js
Date: 7/24/2007 11:55:29 AM
Comment: Hello-
This is an excellent article. Thank you! I need a few additional features in my spreadsheet. 1. mentioned in several other feedbacks, is the ability to export multiple gridviews to different spreadsheets in the same workbook 2. does anyone know how to lock certain columns down in the spreadsheet after you load the data? Please post! Thank you, JS |
|
|
|
|
|
Subject: RE: Multiple SpreadSheets
Name: AzamSharp
Date: 7/24/2007 1:08:01 PM
Comment: Dear All,
At this point I have not came across a solution or code that exports the Excel file into multiple spreadsheets. If I come across such solution I will definitely post the solution here. |
|
|
|
|
|
Subject: Excellent!
Name: Janardhan
Date: 8/6/2007 1:22:43 AM
Comment: Works like a charm! A very practical article devoid of unnecessary jargon. |
|
|
|
|
|
Subject: Problem After Export to Excel
Name: Saad
Date: 8/7/2007 3:13:33 AM
Comment: Hi,
Im using export to excel in asp.net 2.0 gridview the export to excel works fine but after export to excel the application becomes irresponsive. Can u plz help me |
|
|
|
|
|
Subject: RE: Problem in export to excel
Name: AzamSharp
Date: 8/10/2007 2:12:06 PM
Comment: Hi Saad,
You will need to narrow down the problem. Please paste your code so I can take a lot at it.
Thanks, |
|
|
|
|
|
Subject: VB.net code to export data from gridview to Excel
Name: Maria Hobbs
Date: 8/14/2007 12:36:16 PM
Comment: Hi,
Is the code available in vb.net to export data from a gridview to Excel?
Thanks. |
|
|
|
|
|
Subject: ItemDatabound
Name: Bgirl
Date: 8/24/2007 6:57:51 AM
Comment: This worked great! I am having trouble with gvUsers_RowDataBound() though. I have converted this to vb.net but it is always setting my first column to text, not the desired ones. I have a feeling ListItemType.Item is wrong. This is urgent, here is my code. Private Sub dgReport_ItemDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.DataGridItemEventArgs) Handles dgReport.ItemDataBound
If e.Item.ItemType = ListItemType.Item Then
e.Item.Cells(8).Attributes.Add("class", "text")
e.Item.Cells(28).Attributes.Add("class", "text")
e.Item.Cells(29).Attributes.Add("class", "text")
End If
End Sub
Can anyone help? |
|
|
|
|
|
Subject: Problem with exporting
Name: Kenneth
Date: 9/12/2007 1:13:11 PM
Comment: The thing that happens to me is that when i exporte large numbers of records it does not mantein the format of the column on all rows.
Suddenly it goes from number to text and the cells shows an green error arrow saying that the number is stores as text.
why?? |
|
|
|
|
|
Subject: RE: Problem with exporting
Name: AzamSharp
Date: 9/13/2007 4:20:00 AM
Comment: Hi Kenneth,
In order to keep the formatting you will need to inject the CSS into the rows of the GridView. I have explained the approach in this article and also created a video which explains how to accomplish it. You can watch the video at the following URL:
http://gridviewguy.com/ArticleDetails.aspx?articleID=274 |
|
|
|
|
|
Subject: about images?
Name: Tito J. Morales
Date: 9/14/2007 11:43:18 AM
Comment: Hi first i want to say thanks for the great work you are doing, most of your articles are amazing!.
Sorry, but I havent see this kind of implementation: I have a gridview with images wich simulate a "traffic light", in som rows I draw a red.gif in another maybe a yellow.gif and in the grid is ok, but when i export the images does not get exported to excel, could you give me a suggestion of how I resolve this?
thanks in advance. |
|
|
|
|
|
Subject: RE: export images
Name: AzamSharp
Date: 9/14/2007 2:13:00 PM
Comment: Hi Tito J. Morales,
I will try to make an example that solves this problem.
|
|
|
|
|
|
Subject: RE: export images
Name: AzamSharp
Date: 9/14/2007 3:10:31 PM
Comment: Hi Tito J. Morales,
When exporting GridView to excel with images you should use the image path located on the server. This means you should use http:[image path on the server].
This should display the images when exporting the data to excel spreadsheet. |
|
|
|
|
|
Subject: Thank
Name: Ujval
Date: 9/26/2007 3:08:11 AM
Comment: Really Good Code..
I solved my problem from your blog.. |
|
|
|
|
|
Subject: to export the same fonts as well
Name: ambika
Date: 10/1/2007 12:36:21 AM
Comment: Hi ,
Excellent example.
However i would request you to provide me code so that i can export the data as well as the exact font into the excel sheet.
For example if column has bold italic the the excel should also have the same |
|
|
|
|
|
Subject: RE: to export the same fonts as well
Name: AzamSharp
Date: 10/1/2007 2:27:35 PM
Comment: Hi Ambika,
For this purpose you will need to attach more styles to the response. Make the XLS file using Excel and then change the font to bold or whatever you like. Save the XLS file as an XML file and look through the code for the style. The same style you will need to inject in the response to get this work. |
|
|
|
|
|
Subject: Gridview to Excel
Name: Venkat
Date: 10/22/2007 4:54:39 AM
Comment: Really Very Good, after a long search in google to all the site, i found a goog solution expecially "Enable Event Validation=false" i cant expect this, thank u thank u for your kind process,
thanks lot to gridviewguys |
|
|
|
|
|
Subject: reading from data grid to excel n back to data grid
Name: Nagalaxmi
Date: 10/25/2007 4:45:48 AM
Comment: Hi,
I have an excel sheet, I was able to successfully read that into the gridview.And also able to read the data from gridview to the excel file(myexcel), but when i changed the name of that excel file(myxel), n tried to read it into the gridview, I got error..pls help |
|
|
|
|
|
Subject: style
Name: Kenneth
Date: 12/11/2007 8:06:21 AM
Comment: i did like this
Dim style As String = " "
then on RowDataBound
If e.Row.RowType = DataControlRowType.DataRow Then
e.Row.Cells(5).Attributes.Add("class", "number")
e.Row.Cells(6).Attributes.Add("class", "number")
e.Row.Cells(7).Attributes.Add("class", "number")
e.Row.Cells(8).Attributes.Add("class", "number")
e.Row.Cells(9).Attributes.Add("class", "number")
e.Row.Cells(10).Attributes.Add("class", "number")
e.Row.Cells(11).Attributes.Add("class", "number")
e.Row.Cells(12).Attributes.Add("class", "number")
End If
it works on the first 6000 registers but then i goes back to text and in excel it gives an error on the cell sayin that the number is stored as text?? |
|
|
|
|
|
Subject: Leading zeros
Name: Bob
Date: 12/21/2007 6:58:48 AM
Comment: Don't overlook the fact that
protected void gvUsers_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.Cells[1].Attributes.Add("class", "text");
}
}
will only keep the leading zeros in column 1. To keep the leading 0's in another column you need to change the e.Row.Cells[?]... bit to the column you are interested in. |
|
|
|
|
|
Subject: RE: Leading Zeros
Name: AzamSharp
Date: 12/29/2007 6:21:17 PM
Comment: Thanks Bob! |
|
|
|
|
|
Subject: Saving Excel File
Name: Alan Fuller
Date: 2/22/2008 12:36:05 PM
Comment: I love your article and this works great. Is there a way to automatically save the Excel file to a specific location rather than have the user choose where to save the file? |
|
|
|
|
|
Subject: Nice article
Name: Soni
Date: 2/25/2008 10:44:58 PM
Comment: Hah! I was confused with the 2+2 = :) then realised its a check on the website ..
anyways ur website is cool and i generally come here first when I'm stuck with anything related to grids ..
My current issue is this ..
After I used ur code, the excel that I'm saving comes upto 8 MB. If I open the excel and again do a save as , it comes down about 2.5 MB. I opened both the excels in noptepad and the difference I found is that the 8 MB file has all the html tages in it ..
Any idea on how I can resolve this..?
Pls do let me know ..
Thanks and keep up the good work! |
|
|
|
|
|
Subject: Style
Name: Cathy
Date: 3/6/2008 12:59:00 AM
Comment: Hi, I've encounter the same problem as Kenneth's one. When i exported a large numbers of records it does not maintain the format of the column on all rows.
Suddenly it goes from number to text and the cells shows an green error arrow saying that the number is stores as text.
Then I tried to follows AzamSharp's advice. Inject CSS in row of GridView.
protected void FullListDataGrid_OnRowBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.Cells[1].Attributes.Add("class", "text");
e.Row.Cells[0].Attributes.Add("class", "integer");
e.Row.Cells[1].Attributes.Add("class", "text");
e.Row.Cells[21].Attributes.Add("class", "integer");
e.Row.Cells[22].Attributes.Add("class", "integer");
e.Row.Cells[25].Attributes.Add("class", "integer");
e.Row.Cells[28].Attributes.Add("class", "decimal");
}
}
However, the problem couldn't be solved. Any Idea?
Please Help. Thanks in advance.
|
|
|
|
|
|
Subject: Display data in grid in another web-form
Name: Aditi
Date: 3/11/2008 1:36:29 PM
Comment: In a web-form i am collecting data on button click event.Now i wish to display this collected data in a grid in other webform. I tried the following code, using session variable but not getting answer
conn = new SqlConnection(str);
adp = new SqlDataAdapter("select * from flightinfo where origin='" + DropDownSource.SelectedItem.Text + "'and destination='" + DropDownDestination.SelectedItem.Text + "'and class='" + DropDownList3.SelectedItem.Text + "'and flighttime='" + txtOneWay.Text + "'", conn);
DataSet ds = new DataSet();
adp.Fill(ds, "flightinfo");
Session["data"] = ds;
Response.Redirect("DisplayDetails.aspx");
and in the Page_Load od display_details form
GridView1.DataSource = Session["data"];
GridView1.DataBind(); |
|
|
|
|
|
Subject: Great Help
Name: VM
Date: 3/12/2008 7:22:39 AM
Comment: Hello Buddy
It has solved out all problems I faced.
Thanks for this excellent article.
Regards,
Newbie |
|
|
|
|
|
Subject: RE: Great Help
Name: AzamSharp
Date: 3/12/2008 8:32:59 PM
Comment: Hi,
I am glad you liked it! |
|
|
|
|
|
Subject: good artical
Name: suman
Date: 3/14/2008 11:23:41 AM
Comment: good artical..it is very useful |
|
|
|
|
|
Subject: Thanks
Name: David
Date: 3/26/2008 7:02:49 AM
Comment: Thanks for this article. I had "leading zero" problem. This article helped me to solve the problem.
Thanks again!! |
|
|
|
|
|
Subject: Export toExcel 2000
Name: olevin
Date: 3/28/2008 2:11:24 PM
Comment: I have it working fine with Excel 2003 but when I tried it on a computer running office 2000 it doesn't save it as the file name I set it to in code rather it gets the fine name somehow from the webpage's filename. Also it doesn't know it is an excel file unless you type in .xls at the end of the file name.
Here is my code:
strFileName = "ConfirmedReservationReport_" & Date.Now.ToShortDateString & "_" & Date.Now.ToShortTimeString
Response.ClearContent()
Response.AddHeader("content-disposition", "attachment; filename=" & strFileName & ".xls")
'Response.ContentType = "application/excel"
Response.ContentType = "application/vnd.xls"
Dim sw As New StringWriter
Dim htw As New HtmlTextWriter(sw)
Dim frm As New HtmlForm
Me.Controls.Add(frm)
frm.Controls.Add(grdReports)
frm.RenderControl(htw)
' grdReports.RenderControl(htw)
Response.Write(sw.ToString())
Response.End() |
|
|
|
|
|
Subject: Leading Zero's
Name: jtzako
Date: 4/2/2008 10:53:28 AM
Comment: My gridview is generated dynamically for the excel export and I tried to use your 'style' code to prevent it from removing leading zero's. However, it doesnt seem to work.
I get no errors, but the text format is still 'general' |
|
|
|
|
|
Subject: RE: Leading Zero's
Name: AzamSharp
Date: 4/3/2008 2:31:33 PM
Comment: Hi jtzako,
Please post your code so I have a look at it and decide where things are going wrong. |
|
|
|
|
|
Subject: Is there a direct path to export?
Name: Liza
Date: 4/22/2008 12:55:26 AM
Comment: Hi this article is superb & it works. Thkz. But i have a qs is there a way whereby when the user clicks saves it bypass the Save As dialog box and straight away saves to a specified location? Any codes or command that is able to do that? Coz i want to restrict the user from changing the file name. |
|
|
|
|
|
Subject: RE: Is there a direct path to export
Name: AzamSharp
Date: 4/22/2008 10:05:19 AM
Comment: Hi Liza,
I don't think there is a way to do that since this is a browser feature and not the ASP.NET feature. |
|
|
|
|
|
Subject: Clearing textbox inside a gridview?
Name: Liza
Date: 4/23/2008 4:08:21 AM
Comment: Hi Azam, thkz for your reply. I have another qs, is it possible to clear the textbox inside a gridview at the edittemplate region? |
|
|
|
|
|
Subject: Clear textbox inside a gridview?
Name: Liza
Date: 4/23/2008 4:13:37 AM
Comment: Hi Azam, thkx for your reply. I have another qs, is it possible to clear the user's input in the textbox inside a gridview within the the editttemplate region? |
|
|
|
|
|
Subject: Unable to read file
Name: JD
Date: 4/25/2008 1:33:52 PM
Comment: I am getting a unable to read file in excel 2002 and excel 2003, and a warning message in Excel 2007. I am using the same code as you have above and not exactly sure what it is that going wrong. |
|
|
|
|
|
Subject: gridview with paging
Name: Rahul
Date: 4/30/2008 4:32:21 AM
Comment: hello azam sir
Code is working
but when i am exporting all the data of the gridvieew with paging support an error is arrising
RegisterForEventValidation can only be called during Render();
but after removing the paging the code is working fine
i want to export all the data of the gridview with paging in gridview. |
|
|
|
|
|
Subject: RE: GridView with Paging
Name: AzamSharp
Date: 4/30/2008 9:21:00 AM
Comment: Hi,
Check out the following post:
http://geekswithblogs.net/AzamSharp/archive/2006/01/09/65368.aspx
|
|
|
|
|
|
Subject: its really useful
Name: mayank
Date: 5/6/2008 11:32:17 AM
Comment: it was really helpful..
i am really thankful to u |
|
|
|
|
|
Subject: thank you
Name: David
Date: 5/22/2008 10:52:38 AM
Comment: Works flawlessly |
|
|
|
|
|
Subject: DisableControls
Name: Agnes Loyola
Date: 5/27/2008 3:39:12 AM
Comment: hi
I read many of ur article everything is good.Keep on doing these great things.
A long time am searching for to export details from all pages of a gridview to excel sheet.i got the codings from the link given in this feedback.Its works fine.thanks a lot.
I tried to do the DisableControls for TextBox. But it not working.In my Gridview aColumn field is with TexBox multiline.I used the same as that given here.Instead of LinkButton I used TextBox .But no results.My excel shows it as a multiline .Please help me to make its approach to single line |
|
|
|
|
|
Subject: thanks
Name: luba
Date: 5/29/2008 12:52:31 AM
Comment: thanks, it was very helpfull |
|
|
|
|
|
Subject: Excel - Read Only
Name: Agnes Loyola
Date: 6/8/2008 11:15:24 PM
Comment: How to make the exported report to read only.So that no one can edit any rows. |
|
|
|
|
|
Subject: problem with paging
Name: andres
Date: 7/2/2008 10:10:57 AM
Comment: hi
i have a problem
when i run your example and i try to paging i get this error:
Server Error in '/GridViewExportToExcelAllYouNeed' Application.
--------------------------------------------------------------------------------
The GridView 'gvUsers' fired event PageIndexChanging which wasn't handled.
Why? |
|
|
|
|
|
Subject: re: problem with paging
Name: AzamSharp
Date: 7/5/2008 9:30:15 AM
Comment: Hi Andres,
It seems like you are not handling the PageIndexChanging event. Make sure you handle this event and it will work fine. Go to the designer and see the properties of the GridView to handle the event. |
|
|
|
|
|
Subject: Saving the excel file to a particular specified location
Name: Jigar Mehta
Date: 8/25/2008 11:20:37 AM
Comment: This is really a wonderful code.I have used it in my school project. But I have a problem.
What changes I need to do in this code block so that I can store the file to a specific location.
Thank You for the help
Response.AddHeader("content-disposition", "attachment; filename=MyExcelFile.xls");
Response.ContentType = "application/excel";
This is really a wonderful code.I have used it in my school project. But I have a problem.
What changes I need to do in this code block so that I can store the file to a specific location.
Thank You for the help
Response.AddHeader("content-disposition", "attachment; filename=MyExcelFile.xls");
Response.ContentType = "application/excel";
|
|
|
|
|
|
Subject: RE: Saving Excel File to Particular Position
Name: AzamSharp
Date: 8/25/2008 8:04:07 PM
Comment: Hi Jigar Mehta,
You cannot control where the file is saved. ASP.NET is server side and it cannot access the client side. |
|
|
|
|
|
Subject: Export To Excel
Name: Jigar Mehta
Date: 9/4/2008 11:26:23 AM
Comment: Hello,
I had another question. What modifications are necessary to be done in your code block if need to
export data from 3 different gridviews in 1 excel file.
Can you please help me on this.
Thanks
Jigar |
|
|
|
|
|
Subject: re: Export to Excel
Name: AzamSharp
Date: 9/9/2008 8:24:22 PM
Comment: Hi Jigar Mehta,
Good question! For scenarios where you want to export 2-3 GridViews into a single Excel you have to think about the underlying datasource. If the GridViews are using DataSets then you need to combine all the DataSets together and then export to excel.
|
|
|
|
|
|
Subject: how to use header and footer in Gried view?
Name: kanchan
Date: 9/15/2008 3:24:15 AM
Comment: please help me how to use header and footer in Gried view? |
|
|
|
|
|
Subject: extacts/imports contacts from gmail, yahoo etc...
Name: saleem
Date: 10/1/2008 12:31:25 AM
Comment: Hi sir,
please help me, to complete my task, any related links or articles send to me sir, imports contacts from gmail to our application. |
|
|
|
|
|
Subject: Thanks
Name: Vikil
Date: 10/9/2008 3:49:08 AM
Comment: Hey this works gr8 .. had a prob initially but works wonderfully...
cheers to u |
|
|
|
|
|
Subject: Using the Sybase ASEClient with GridView
Name: Rebecca Pitts
Date: 10/29/2008 2:43:19 PM
Comment: I have applied the ASEClient from Sybase to retrieve data. I would like to limit the Number of rows using Page size but it does not recognize it. What can I do to limit the number of rows displayed in the gridview if the page size does not work?
Thanks,
Rebecca |
|
|
|
|
|
Subject: So Easy!
Name: Regin
Date: 11/17/2008 10:41:29 AM
Comment: Thanks Azam! You have made it so easy... Keep sharing this gift you have! |
|
|
|
|
|
Subject: colours moved
Name: Nat
Date: 11/24/2008 10:53:28 AM
Comment: I'm having an issue when I apply the CSS to my Excel export; the colour of the header and alternate rows are not applied. Rather, they are applied to the blank area to the left of the data in the Excel spreadsheet. I would like to get rid of the colour altogether. How do I do that? |
|
|
|
|
|
Subject: Leading Zeros
Name: Aidan Host
Date: 11/28/2008 2:30:19 AM
Comment: Thank you for the code samples.
To display leading zero's use the style string as well as setting the column's class to text. The column index is zero-based. |
|
|
|
|
|
Subject: Excellent article!
Name: gina
Date: 12/17/2008 11:32:34 AM
Comment: You article is very useful..Thank you.
Do you know how to export a gridview to pdf format? |
|
|
|
|
|
Subject: re: Exporting GridView to PDF
Name: Mohammad Azam
Date: 12/17/2008 1:10:39 PM
Comment: I will try to write an article on how to export GridView to PDF. |
|
|
|
|
|
Subject: Save Excel file at given path
Name: umesh
Date: 12/18/2008 3:20:56 AM
Comment: Currently excel file is saving at Temp folder.I want to save it at my given path. How can i do that ? |
|
|
|
|
|
Subject: thanks!
Name: mark
Date: 1/6/2009 2:01:08 PM
Comment: Very helpful. Thanks!!! |
|
|
|
|
|
Subject: Excellant Article........
Name: Renu
Date: 1/15/2009 11:03:07 AM
Comment: Very nice article.............. I will recomend this site for my .Net friends |
|
|
|
|
|
Subject: Excellant post!!!!!
Name: AxleWack
Date: 2/11/2009 11:43:47 AM
Comment: Ive been searching for a solution like this the entire day! 7am - 10pm. Thank you!!!! |
|
|
|
|
|
Subject: How can I set the print area
Name: Monty
Date: 3/7/2009 11:39:53 PM
Comment: I'd like to set the print area in the Excel. For example It would be nice to have Excel automatically adjust the print area to include all the columns in the gridview instead of having them overflow into other pages. Is this possible? |
|
|
|
|
|
Subject: Corrupt File Format
Name: Nick Owens
Date: 3/20/2009 12:09:12 PM
Comment: Great article! I needed to download the code and take a run through since it wasn't working right off the bat. I had to wrap everything in a form element which I hadn't added to this page yet since there were no other actionable items.
When I attempt to open the file in Excel 2007 (Vista), I get a message about the file being in an apparently 'corrupt' format. I can choose to open the file anyways but that Microsoft recommends I do not open it. It opens fine if I choose to ignore the warning. Any way around that? |
|
|
|
|
|
Subject: RE: Nick Owens
Name: Mohammad Azam
Date: 3/26/2009 7:26:02 AM
Comment: Hi Nick Owens,
Yes, I have seen a similar issue dealing with Word 2007. I have not yet found a solution to that problem. If you come across the solution please post it under comments. |
|
|
|
|
|
Subject: looking zip format
Name: anuj
Date: 3/29/2009 3:44:34 AM
Comment: dat are exported. but i m looking it should save as zip format. |
|
|
|
|
|
Subject: Thanks
Name: Preetham
Date: 4/15/2009 12:49:28 PM
Comment: U really Rock,,
all ur Code Works Properly |
|
|
|
|
|
Subject: Arabic Data
Name: Noor
Date: 4/26/2009 12:32:35 AM
Comment: Hi,
Thanks for the code. I have the grid with arabic data. The arabic text displays correctly on the page but when exporting to excel, it is corrupted. Plz. Help
Thanks,
Noor |
|
|
|
|
|
Subject: re: Arabic Data
Name: Mohammad Azam
Date: 4/26/2009 4:46:26 PM
Comment: Hi Noor,
First, try to display Arabic data in Excel without .NET code. Once, you have got that working you need to save the Excel file as XML file and view the source. Finally, you need to parse out the Arabic part from the XML and then add that to response stream as a style. |
|
|
|
|
|
Subject: GridView Export ot Excel
Name: Michael Finch
Date: 5/26/2009 7:25:44 AM
Comment: I am using Visual Studio 2008 .Net 3.0.
The line of code on the export button click (GridView1.RenderControl(htw);
Gives me the following exception: Gridview must be placed inside a tag with runat=server.
The code complies OK and application runs, I get the above exception when I click the Exprt Button.
Thanks for a great website.
|
|
|
|
|
|
Subject: thanx
Name: Ala
Date: 6/21/2009 10:11:18 PM
Comment: thank you a lot this topic was very helpful. |
|
|
|
|
|
Subject: Exporting accented letters
Name: Cesar
Date: 8/25/2009 9:37:54 AM
Comment: Hi, excellent post, it really works, but I have a question though,when I export letters like é,ó,á,í,ú, etc I get a funny character, ie for á I get á, so how can I export those correctly,
thanks |
|
|
|
|
|
Subject: Thank yo very much
Name: Ali
Date: 9/9/2009 3:59:52 AM
Comment: simply superb dear friend. thank you very much for the article. |
|
|
|
|
|
Subject: does not work when in a Usercontrol
Name: Bart
Date: 11/24/2009 7:30:32 AM
Comment: RenderControl does not work when the gridview is in a user control |
|
|
|
|
|
Subject: Export to Excel with decimal
Name: Suresh Kumar kushwha
Date: 12/1/2009 10:56:17 PM
Comment: This is excellent code |
|
|
|
|
|
Subject: Saving leading zeros in excelsheet while exporting through C#.net?
Name: Varun
Date: 12/17/2009 1:21:30 AM
Comment: NA |
|
|
|
|
|
Subject: Gr8 Article
Name: Nilanjan Saha
Date: 1/14/2010 11:07:16 PM
Comment: Thanks a lot. It was of great help |
|
|
|