473,804 Members | 2,064 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

DataGrid Contents to Excel - Advanced Methods

Hi,

I am trying to export the contents of a DataGrid to Excel. I have already
found the following articles:

http://support.microsoft.com/default...b;en-us;317719
http://www.c-sharpcorner.com/Code/20...ridToExcel.asp

These methods _only_ work if the following is true:

1.) Paging and sorting is disabled; (produces error stating that controls
must reside within form tag and specify runat=server)
2.) Columns are autogenerated (unless see 3);
3.) If columns are not autogenerated template columns in the form of the
following causes errors; (cannot alter controls that contain <% %>;

<asp:TemplateCo lumn HeaderText="Day ">
<ItemTemplate >
<%# DataBinder.Eval (Container, "DataItem.DayOf Week") %>
</ItemTemplate>
</asp:TemplateCol umn>

The Code I am using is at the bottom of this post.

I was wondering how to go about the following - or if there is a 3rd party
control that does this.

Either:

1.) Pass the original datasource to some kind of custom control. This would
also be given the properties of the datasource (in my case strongly typed
collections) and the control would then loop through using reflection to
Retrieve the values and generate a new HtmlTable that is then rendered to
the Response stream.

2.) Contruct a new grid using the original and only constructing columns
specified (not sure how to manually create a grid yet.)

The first I beleive is far more extensible as it allows my object model and
any available property in it to be exported to excel, but obviously this
will have a longer dev time. Is this even possible.

Any help would be greatly appreciated.

TIA

MattC
protected void ExportToExcel(D ataGrid grid)
{
Response.Clear( );
Response.Buffer = true;
Response.Conten tType = "applicatio n/vnd.ms-excel";
Response.Charse t = String.Empty;
this.EnableView State = false;

System.IO.Strin gWriter oStringWriter = new System.IO.Strin gWriter();
System.Web.UI.H tmlTextWriter oHtmlTextWriter = new
System.Web.UI.H tmlTextWriter(o StringWriter);

this.ClearContr ols(grid);
grid.RenderCont rol(oHtmlTextWr iter);

Response.Write( oStringWriter.T oString());

Response.End();
}

protected void ClearControls(C ontrol control)
{
for (int i=control.Contr ols.Count -1; i>=0; i--)
{
ClearControls(c ontrol.Controls[i]);
}

if (!(control is TableCell))
{
if (control.GetTyp e().GetProperty ("SelectedItem" ) != null)
{
LiteralControl literal = new LiteralControl( );
control.Parent. Controls.Add(li teral);
try
{
literal.Text =
(string)control .GetType().GetP roperty("Select edItem").GetVal ue(control,null );
}
catch
{
}
control.Parent. Controls.Remove (control);
}
else
if (control.GetTyp e().GetProperty ("Text") != null)
{
LiteralControl literal = new LiteralControl( );
control.Parent. Controls.Add(li teral);
literal.Text =
(string)control .GetType().GetP roperty("Text") .GetValue(contr ol,null);
control.Parent. Controls.Remove (control);
}
}
return;
}

Nov 19 '05 #1
1 1147
pls ignore.

MattC

"MattC" <m@m.com> wrote in message
news:u7******** *****@TK2MSFTNG P15.phx.gbl...
Hi,

I am trying to export the contents of a DataGrid to Excel. I have already
found the following articles:

http://support.microsoft.com/default...b;en-us;317719
http://www.c-sharpcorner.com/Code/20...ridToExcel.asp

These methods _only_ work if the following is true:

1.) Paging and sorting is disabled; (produces error stating that controls
must reside within form tag and specify runat=server)
2.) Columns are autogenerated (unless see 3);
3.) If columns are not autogenerated template columns in the form of the
following causes errors; (cannot alter controls that contain <% %>;

<asp:TemplateCo lumn HeaderText="Day ">
<ItemTemplate >
<%# DataBinder.Eval (Container, "DataItem.DayOf Week") %>
</ItemTemplate>
</asp:TemplateCol umn>

The Code I am using is at the bottom of this post.

I was wondering how to go about the following - or if there is a 3rd party
control that does this.

Either:

1.) Pass the original datasource to some kind of custom control. This
would
also be given the properties of the datasource (in my case strongly typed
collections) and the control would then loop through using reflection to
Retrieve the values and generate a new HtmlTable that is then rendered to
the Response stream.

2.) Contruct a new grid using the original and only constructing columns
specified (not sure how to manually create a grid yet.)

The first I beleive is far more extensible as it allows my object model
and
any available property in it to be exported to excel, but obviously this
will have a longer dev time. Is this even possible.

Any help would be greatly appreciated.

TIA

MattC
protected void ExportToExcel(D ataGrid grid)
{
Response.Clear( );
Response.Buffer = true;
Response.Conten tType = "applicatio n/vnd.ms-excel";
Response.Charse t = String.Empty;
this.EnableView State = false;

System.IO.Strin gWriter oStringWriter = new System.IO.Strin gWriter();
System.Web.UI.H tmlTextWriter oHtmlTextWriter = new
System.Web.UI.H tmlTextWriter(o StringWriter);

this.ClearContr ols(grid);
grid.RenderCont rol(oHtmlTextWr iter);

Response.Write( oStringWriter.T oString());

Response.End();
}

protected void ClearControls(C ontrol control)
{
for (int i=control.Contr ols.Count -1; i>=0; i--)
{
ClearControls(c ontrol.Controls[i]);
}

if (!(control is TableCell))
{
if (control.GetTyp e().GetProperty ("SelectedItem" ) != null)
{
LiteralControl literal = new LiteralControl( );
control.Parent. Controls.Add(li teral);
try
{
literal.Text =
(string)control .GetType().GetP roperty("Select edItem").GetVal ue(control,null );
}
catch
{
}
control.Parent. Controls.Remove (control);
}
else
if (control.GetTyp e().GetProperty ("Text") != null)
{
LiteralControl literal = new LiteralControl( );
control.Parent. Controls.Add(li teral);
literal.Text =
(string)control .GetType().GetP roperty("Text") .GetValue(contr ol,null);
control.Parent. Controls.Remove (control);
}
}
return;
}

Nov 19 '05 #2

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
10930
by: Ugo | last post by:
Hi, I am having a problem exporting a Datagrid to excel in asp.net. For some reason I am getting a blank excel page. I set up in IIS the Mime for ..xls. My code is below any help would be appreciated.. Thanks CODE: private void ExportToExcel()
1
1866
by: Luis Esteban Valencia | last post by:
Here is my aspx code: ============= <%@ Page language="c#" Codebehind="WebForm3.aspx.cs" AutoEventWireup="false" Inherits="PDM.excel.WebForm3" %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" > <HTML> <HEAD> <title>WebForm3</title> <meta content="Microsoft Visual Studio .NET 7.1" name="GENERATOR"> <meta content="C#" name="CODE_LANGUAGE">
2
1756
by: Daniel Walzenbach | last post by:
Hi, I have a question regarding the DataGrid control. If paging is enabled the grid binds the data, sets the paging on the top/bottom (or however it is set up) and throws away unnecessary data. So far so good for a tiny amount of data but if some 100000 of rows are the source this approach is stupid.
0
1742
by: Tim_k | last post by:
Does anyone have an example of how to export a datagrid to an Excel pivot table? The code below exports the grid contents to Excel using the Response object. I'd like to expand it to show the data in a pivot table. Avoiding a 3rd party control is preferable. Thanks, Tim Response.ContentType = "application/vnd.ms-excel" Response.Charset = ""
3
1809
by: nkunkov | last post by:
Hi, I have read a lot of articles in this newsgroup about how to solve this problem but found no solution. I'm trying to export a C# datagrid to Excel file. Here is my code that I have also found on google: MyDataGrid.EnableViewState = false; MyPage.Response.Clear(); MyPage.Response.Buffer = true; MyPage.Response.AddHeader( "Content-disposition",
3
4356
by: Bidarkota | last post by:
When i export DataGrid to Excel all the HTML contents are also exporting to excel. i am using stylesheets in the ASPX Page and i am getting an alert message that stylesheets are missing. i need to export only the contents of the Datagrid to excel. i don't need all other stuff which is present on the page. is there any way to achieve it. Thanks in Advance
5
1835
by: Dave | last post by:
In a VB.NET application, I have a datagrid that I export to an Excel spreadsheet like this: ' Set the content type to Excel Response.ContentType = "application/vnd.ms-excel" Dim tw As New System.IO.StringWriter Dim hw As New System.Web.UI.HtmlTextWriter(tw) ' Get the HTML for the control.
4
3958
by: Frank | last post by:
Hello All, I ham using VS.NET 2003. Have followed instructions from http://gridviewguy.com/ArticleDetails.aspx?articleID=26 along with several other articles to no avail. I am pulling my hair out at this point. What I have is this : Members.aspx file:
3
1837
by: Mike | last post by:
Hello, I am attempting to export the contents of a datagrid on my webform (using Excel automation) through ASP.NET. I have added the Excel object library to my VS ASP.NET project but I am lost on how to export my datagrid contents to Excel? I am sure it can be done but having difficulties figuring out the code.
0
9716
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9595
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10604
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10101
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
7643
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6870
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5536
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5675
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
3005
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.