将datagrid数据导到excel的一个问题

前几天,从 fengzhimei   那里看到一篇在 asp.net将 datagrid中的数据导到excel中的文章 ,今天有空试了试,发现在导出有排序功能的表格的出现问题(设置模板列也会存在问题):在运行加载页面时,提示 datagrid中的某些列 必须放在 runat=server 的form中。

csdn中有人问这样的问题,好像都没有解决,查了一些资料,发现这是由于datagrid中的控件引起的,需要在运行的时候删除这些控件。 在 http://www.c-sharpcorner.com/Code/2003/Sept/ExportASPNetDataGridToExcel.asp 里有详细的说明,我贴出源代码:
WebForm1.aspx:

<%@ Page language="c#" Codebehind="WebForm1.aspx.cs" AutoEventWireup="false" Inherits="Webtest.WebForm1" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
<HTML>
    
<HEAD>
        
<title>WebForm1</title>
        
<meta name="GENERATOR" Content="Microsoft Visual Studio .NET 7.1">
        
<meta name="CODE_LANGUAGE" Content="C#">
        
<meta name="vs_defaultClientScript" content="JavaScript">
        
<meta name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5">
    
</HEAD>
    
<body MS_POSITIONING="GridLayout">
        
<form id="Form1" method="post" runat="server">
            
<FONT face="宋体">
                
<asp:Button id="Button1" style="Z-INDEX: 101; LEFT: 152px; POSITION: absolute; TOP: 80px" runat="server"
                    Text
="Button" Width="168px" Height="56px"></asp:Button>
                
<asp:DataGrid id="DataGrid1" style="Z-INDEX: 102; LEFT: 56px; POSITION: absolute; TOP: 160px"
                    runat
="server" Width="363px" Height="195px"></asp:DataGrid></FONT>
        
</form>
    
</body>
</HTML>


WebForm1.aspx.cs
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;


namespace Webtest
{
    
/// <summary>
    
/// WebForm1 的摘要说明。
    
/// </summary>

    public class WebForm1 : System.Web.UI.Page
    
{
        
protected System.Web.UI.WebControls.DataGrid DataGrid1;
        
protected System.Web.UI.WebControls.Button Button1;
    
        
private void Page_Load(object sender, System.EventArgs e)
        
{
            
// 在此处放置用户代码以初始化页面
            if (!IsPostBack)
            
{

                SqlConnection conn 
= new SqlConnection ("data source=(local);initial catalog=Northwind;Pwd=;User ID=sa");
                SqlCommand cmd 
= new SqlCommand ("Select LastName, FirstName, Title, TitleOfCourtesy, BirthDate, HireDate, Address, City, Region, PostalCode, Country from Employees", conn);
                SqlDataAdapter da 
= new SqlDataAdapter(cmd);
                DataSet ds 
= new DataSet();
                da.Fill(ds);
                DataGrid1.DataSource 
= ds.Tables[0];
                DataGrid1.DataBind();
            }

        }


        
Web 窗体设计器生成的代码

        
private void Button1_Click(object sender, System.EventArgs e)
        
{
//            Response.Write("<script language='javascript'>window.open('WebForm3.aspx')</script>");


            Response.Clear();
            Response.Buffer
= true;
            Response.ContentType 
= "application/vnd.ms-excel";
            Response.Charset 
= "";
            
this.EnableViewState = false;

            System.IO.StringWriter oStringWriter 
= new System.IO.StringWriter();
            System.Web.UI.HtmlTextWriter oHtmlTextWriter 
= new System.Web.UI.HtmlTextWriter(oStringWriter);

            
this.ClearControls(DataGrid1);
            DataGrid1.RenderControl(oHtmlTextWriter);

            Response.Write(oStringWriter.ToString());

            Response.End();

        }


        
        
private void ClearControls(Control control)
        
{
            
for (int i=control.Controls.Count -1; i>=0; i--)
            
{
                ClearControls(control.Controls[i]);
            }


            
if (!(control is TableCell))
            
{
                
if (control.GetType().GetProperty("SelectedItem"!= null)
                
{
                    LiteralControl literal 
= new LiteralControl();
                    control.Parent.Controls.Add(literal);
                    
try
                    
{
                        literal.Text 
= (string)control.GetType().GetProperty("SelectedItem").GetValue(control,null);
                    }

                    
catch

                    
{

                    }


                    control.Parent.Controls.Remove(control);
                }


                
else

                    
if (control.GetType().GetProperty("Text"!= null)
                
{
                    LiteralControl literal 
= new LiteralControl();
                    control.Parent.Controls.Add(literal);
                    literal.Text 
= (string)control.GetType().GetProperty("Text").GetValue(control,null);
                    control.Parent.Controls.Remove(control);
                }

            }

            
return;
        }


    }

}

posted on 2004-07-23 17:15  wljcan  阅读(5401)  评论(13编辑  收藏  举报

导航