感谢您使用微软产品。请参考下面的例子代码:
//Set the content type to Excel.
Response.ContentType = "application/vnd.ms-excel";//Remove the charset from the Content-Type header.
Response.Charset = "";//Turn off the view state.
this.EnableViewState= false;System.IO.StringWriter tw = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(tw);//Get the HTML for the control.
this.DataGrid1.RenderControl(hw);//Write the HTML back to the browser.
Response.Write(tw.ToString());//End the response.
Response.End();完整的关于如何从ASP.NET的DataGrid导出到Excel文件的例子,请参照:
http://support.microsoft.com/default.aspx?scid=kb;en-us;Q317719&SD=MSKB&希望能对您有所帮助!======================
- 微软全球技术中心本贴子仅供CSDN的用户作为参考信息使用。其内容不具备任何法律保障。您需要考虑到并承担使用此信息可能带来的风险。具体事项可参见使用条款(http://support.microsoft.com/directory/worldwide/zh-cn/community/terms_chs.asp)。
为了为您创建更好的讨论环境,请参加我们的用户满意度调查(http://support.microsoft.com/directory/worldwide/zh-cn/community/survey.asp?key=(S,49854782))。
======================

解决方案 »

  1.   

    感谢freesoul_ms([微软] 最后的白鸟) 的回答:它所给的示例是asp.net(用vb实现),而我现在是用asp.net(用c#实现),依照http://support.microsoft.com/default.aspx?scid=kb;en-us;Q317719&SD=MSKB&的例子我更改后,不成功(在这之前我已经式过了,代码几乎和上面(最后的白鸟)的一摸一样),按照阁下的代码也不成功。错误现象是:好象Response.Write(tw.ToString());没有起作用,有没有这条指令都无所谓。你必须在Response.End();前加上一句 Response.Write("测试,无用的数据0000"),只要你加上了Response.Write("...."),在导出的excel中就有<table>对象中的类容,有文本框的Text属性的值,有label的Text值,其它的控件如:DataGrid就没有。相反,如果你在Response.End();前没有加上Response.Write("....")这句话,则在在导出的excel中什么都没有,一偏空白。
    另外:在try .... Catch() ...中执行Response.End();这条语句时要出错。
      

  2.   

    感谢freesoul_ms([微软] 最后的白鸟) 的回答:它所给的示例是asp.net(用vb实现),而我现在是用asp.net(用c#实现),依照http://support.microsoft.com/default.aspx?scid=kb;en-us;Q317719&SD=MSKB&的例子我更改后,不成功(在这之前我已经式过了,代码几乎和上面(最后的白鸟)的一摸一样),按照阁下的代码也不成功。错误现象是:好象Response.Write(tw.ToString());没有起作用,有没有这条指令都无所谓。你必须在Response.End();前加上一句 Response.Write("测试,无用的数据0000"),只要你加上了Response.Write("...."),在导出的excel中就有<table>对象中的类容,有文本框的Text属性的值,有label的Text值,其它的控件如:DataGrid就没有。相反,如果你在Response.End();前没有加上Response.Write("....")这句话,则在在导出的excel中什么都没有,一偏空白。
    另外:在try .... Catch() ...中执行Response.End();这条语句时要出错。
      

  3.   


    To: zcw_net(我睡了)您添加了这句代码了么?
    this.DataGrid1.RenderControl(hw);
    并请确认您程序中的tw.ToString())不是空字符串。另外一个建议,您可以一步步按照http://support.microsoft.com/default.aspx?scid=kb;en-us;Q317719&SD=MSKB&的例子代码进行操作,试一下是否成功。希望能对您有所帮助!======================
    - 微软全球技术中心本贴子仅供CSDN的用户作为参考信息使用。其内容不具备任何法律保障。您需要考虑到并承担使用此信息可能带来的风险。具体事项可参见使用条款(http://support.microsoft.com/directory/worldwide/zh-cn/community/terms_chs.asp)。
    为了为您创建更好的讨论环境,请参加我们的用户满意度调查(http://support.microsoft.com/directory/worldwide/zh-cn/community/survey.asp?key=(S,49854782))。
    ======================
      

  4.   

    感谢freesoul_ms([微软] 最后的白鸟) :
        你上面的代码确实都已经在我的cs文件中已经有了,在调用  this.DataGrid1.RenderControl(hw);后确实tw.ToString()是空字符串。但这无关紧要,直接用Response.Write("测试测试测试")它在Excel中都输不出“测试测试测试”字符,因此与Response.Write(tw.ToString());无关。只有在aspx中的“table”对象,不是"asp:table"对象才能输出到Excel,源代码:
    webform4.aspx:
    <%@ Register TagPrefix="cc1" Namespace="BuynowDataGrid" Assembly="prjBuynowDataGrid" %>
    <%@ Page language="c#" Codebehind="WebForm4.aspx.cs" AutoEventWireup="false" Inherits="WebApplication9.WebForm4" %>
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
    <HTML>
    <HEAD>
    <title>WebForm4</title>
    <meta name="GENERATOR" Content="Microsoft Visual Studio 7.0">
    <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="WebForm4" method="post" runat="server">
    <asp:datagrid id="ItemsGrid" style="Z-INDEX: 101; LEFT: 17px; POSITION: absolute; TOP: 152px" runat="server" CellPadding="3" BorderWidth="1" BorderColor="black" EnableViewState="False">
    <HeaderStyle BackColor="#00AAAA"></HeaderStyle>
    <Columns>
    <asp:BoundColumn DataField="IntegerValue" HeaderText="Number"></asp:BoundColumn>
    <asp:BoundColumn DataField="StringValue" HeaderText="Description"></asp:BoundColumn>
    <asp:BoundColumn DataField="CurrencyValue" HeaderText="Price" DataFormatString="{0:c}"></asp:BoundColumn>
    </Columns>
    </asp:datagrid>
    <asp:Button id="Button1" runat="server" Text="ExportToExcel" Width="183px" Height="46px"></asp:Button>
    <table cellpadding="0" cellspacing="0" border="0">
    <tr bgcolor="#3300ff">
    <td>
    dsafds adsf dsfadsf第一行第一列
    </td>
    <td>
    dsafds adsf dsfadsf第一行第二列
    </td>
    <td>
    dsafds adsf dsfadsf第一行第三列
    </td>
    <td>
    dsafds adsf dsfadsf第一行第四列
    </td>
    </tr>
    <tr>
    <td>
    dsafds adsf dsfadsf第二行第一列
    </td>
    <td>
    dsafds adsf dsfadsf第二行第二列
    </td>
    <td>
    dsafds adsf dsfadsf第二行第三列
    </td>
    <td>
    dsafds adsf dsfadsf第二行第四列
    </td>
    </tr>
    </table>
    </form>
    </body>
    </HTML>///////////////////////////////////////////////////////////////////////////
    WebForm4.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;namespace WebApplication9
    {
    /// <summary>
    /// Summary description for WebForm4.
    /// </summary>
    public class WebForm4 : System.Web.UI.Page
    {
    protected System.Web.UI.WebControls.DataGrid ItemsGrid;
    protected System.Web.UI.WebControls.Button Button1;

    private void Page_Load(object sender, System.EventArgs e)
    {
    if (!Page.IsPostBack)
    {
    ItemsGrid.DataSource= CreateDataSource();
    ItemsGrid.DataBind();
    }
    } #region Web Form Designer generated code
    override protected void OnInit(EventArgs e)
    {
    //
    // CODEGEN: This call is required by the ASP.NET Web Form Designer.
    //
    InitializeComponent();
    base.OnInit(e);
    }

    /// <summary>
    /// Required method for Designer support - do not modify
    /// the contents of this method with the code editor.
    /// </summary>
    private void InitializeComponent()
    {    
    this.Button1.Click += new System.EventHandler(this.Button1_Click);
    this.Load += new System.EventHandler(this.Page_Load); }
    #endregion private void Button1_Click(object sender, System.EventArgs e)
    {
    Response.ContentType = "application/vnd.ms-excel";
    //' Remove the charset from the Content-Type header.
    Response.Charset = "";
    //' Turn off the view state.
    this.EnableViewState= false; System.IO.StringWriter tw =new System.IO.StringWriter();
    System.Web.UI.HtmlTextWriter hw =new System.Web.UI.HtmlTextWriter(tw); //' Get the HTML for the control.
    ItemsGrid.RenderControl(hw);

    //' Write the HTML back to the browser.
    Response.Write(hw.ToString()); Response.End();
    }
    ICollection CreateDataSource() 
    {
    DataTable dt = new DataTable();
    DataRow dr;
     
    dt.Columns.Add(new DataColumn("IntegerValue", typeof(Int32)));
    dt.Columns.Add(new DataColumn("StringValue", typeof(string)));
    dt.Columns.Add(new DataColumn("CurrencyValue", typeof(double)));
     
    for (int i = 0; i < 9; i++) 
    {
    dr = dt.NewRow();
     
    dr[0] = i;
    dr[1] = "Item " + i.ToString();
    dr[2] = 1.23 * (i + 1);
     
    dt.Rows.Add(dr);
    }
      DataView dv = new DataView(dt);
    return dv;
    } private void Button2_Click(object sender, System.EventArgs e)
    {
    try
    {
    //Set the content type to Excel.
    Response.ContentType = "application/vnd.ms-excel"; //Remove the charset from the Content-Type header.
    Response.Charset = ""; //Turn off the view state.
    this.EnableViewState= false; System.IO.StringWriter tw = new System.IO.StringWriter();
    System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(tw); //Get the HTML for the control.
    this.ItemsGrid.RenderControl(hw); //Write the HTML back to the browser.
    Response.Write(tw.ToString());
    //此处是不是该用Response.Write(hw.ToString());,但我式了,还是不行。 //End the response.
    Response.End();   //这条指令要出错。 }
    catch(Exception RaiseErr)
    {
    throw(new Exception(RaiseErr.Message.ToString()));
    }
    }
    }
    }