将GridView导出到Excel

时间:2013-09-19 19:38:11

标签: c# asp.net excel gridview

我有一个gridview,其中包含一个按钮,用于将数据导出到Excel文件。单击该按钮时,我收到以下错误:

  

'GridView'类型的控件'gvLogNotice'必须放在带有runat = server的表单标签内。

但是,网格在表单标记内,我使用MasterPage和使用没有MasterPage的页面尝试了它,但仍然得到相同的错误。

这是我的Gridview片段w /按钮:

<form id="form1" runat="server">
 <div style="width:600px;">
       <asp:GridView ID="gvLogNotice" 
        runat="server" 
        AutoGenerateColumns="false" 
        ShowFooter="false"
        OnRowCancelingEdit="gvLogNotice_RowCancelingEdit"
        OnRowEditing="gvLogNotice_RowEditing" 
        OnRowUpdating="gvLogNotice_RowUpdating"
        onpageindexchanging="gvLogNotice_PageIndexChanging"
        OnRowDataBound="gvLogNotice_RowDataBound"
        EmptyDataText="There are no data records to display."
        DataKeyNames="LogNoticeID"
        AllowPaging="true"
        PageSize="10"
        AllowSorting="true"
        OnSorting="gvLogNotice_sorting"
        Width="700px">
        <Columns>
            <asp:TemplateField HeaderText="Log No." Visible="false">
                <ItemTemplate>
                    <%#Eval("LogNoticeID")%>
                </ItemTemplate>
                <EditItemTemplate>
                    <asp:TextBox ID="txtLogNoticeID" runat="server" Enabled="false" Text=' <%#Eval("LogNoticeID") %>'></asp:TextBox>
                </EditItemTemplate>
             </asp:TemplateField>
            <asp:TemplateField HeaderText="Log Date" SortExpression="DateLogged">
                <ItemTemplate>
                    <%#Eval("DateLogged")%>
                </ItemTemplate>
                <EditItemTemplate>
                    <asp:TextBox ID="txtDateLogged" runat="server" Text=' <%#Eval("DateLogged") %>'></asp:TextBox>
                </EditItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="Log Description" HeaderStyle-Width="50px" sortexpression="LogNoticeDescript">
                <ItemTemplate>
                    <%#Eval("LogNoticeDescript")%>
                </ItemTemplate>
                <EditItemTemplate>
                    <asp:TextBox ID="txtLogNoticeDescript" runat="server" Text=' <%#Eval("LogNoticeDescript") %>'></asp:TextBox>
                </EditItemTemplate>
           </asp:TemplateField>
           <asp:TemplateField HeaderText="Responsible Party" sortexpression="ResponsibleParty">
                <ItemTemplate>
                    <%#Eval("ResponsibleParty")%>
                </ItemTemplate>
                <EditItemTemplate>
                    <asp:TextBox ID="txtResponsibleParty" runat="server" Text=' <%#Eval("ResponsibleParty") %>'></asp:TextBox>
                </EditItemTemplate>
          </asp:TemplateField>
             <asp:TemplateField HeaderText="Planned Date" SortExpression="PlannedDate" >
                <ItemTemplate>
                    <%#Eval("PlannedDate")%>
                </ItemTemplate>
                <EditItemTemplate>
                    <asp:TextBox ID="txtPlannedDate" runat="server" Text=' <%#Eval("PlannedDate") %>'></asp:TextBox>
              </EditItemTemplate>
          </asp:TemplateField>
           <asp:TemplateField HeaderText="Case Number" SortExpression="CaseNumber">
                <ItemTemplate>
                    <%#Eval("CaseNumber")%>
                </ItemTemplate>
                <EditItemTemplate>
                    <asp:TextBox ID="txtCaseNumber" runat="server" Text=' <%#Eval("CaseNumber") %>'></asp:TextBox>
              </EditItemTemplate>
          </asp:TemplateField>
             <asp:TemplateField HeaderText="Log Status" SortExpression="LogStatus">
                <ItemTemplate>
                    <%#Eval("LogStatus")%>
                </ItemTemplate>
                <EditItemTemplate>
                    <asp:TextBox ID="txtLogStatus" runat="server" Text=' <%#Eval("LogStatus") %>'></asp:TextBox>
                    <asp:RangeValidator ID="rgvtxtLogStatus" runat="server" ControlToValidate="txtLogStatus" MaximumValue="1" MinimumValue="0" Text="Only a Value of 1 or 0 is allowed." />
                </EditItemTemplate>
          </asp:TemplateField>
            <asp:TemplateField HeaderText="Edit">
                <ItemTemplate>
                    &nbsp;&nbsp;
                    <asp:ImageButton ID="ImageButton1" runat="server" ImageUrl="images/edit.png" Width="25"
                        Height="25" CommandName="Edit" />&nbsp;&nbsp;
                   <%-- <asp:ImageButton ID="ImageButton2" runat="server" ImageUrl="~/img/delete.png" CommandName="Delete"
                        OnClientClick="return confirm('Are you sure want to delete record?')" />--%>
                </ItemTemplate>
                <EditItemTemplate>
                    <asp:LinkButton ID="LinkButton1" runat="server" CommandName="Update">Update</asp:LinkButton>&nbsp;&nbsp;
                    <asp:LinkButton ID="LinkButton2" runat="server" CommandName="Cancel">Cancel</asp:LinkButton>
                </EditItemTemplate>
              </asp:TemplateField>
        </Columns>
    </asp:GridView>
    </div>

<div><asp:Button runat="server" ID="btnExport" Text="Export to Excel" 
            onclick="btnExport_Click" /></div>
</form>

...这是按钮背后的代码:

protected void btnExport_Click(object sender, EventArgs e)
    {


        Response.Clear();

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


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

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

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

    gvLogNotice.RenderControl(htmlWrite);

    Response.Write(stringWrite.ToString());

    Response.End();

    }

......第二种方法:我也尝试了以下内容,我得到一个错误,只有一个表格可能存在:

 protected void btnExport_Click(object sender, EventArgs e)
  {

        try
        {
            Response.ClearContent();
            string attachment = "attachment; filename=MyExelFile.xls";
            Response.ClearContent();
            Response.AddHeader("content-disposition", attachment);
            Response.ContentType = "application/ms-excel";
            StringWriter strWrite = new StringWriter();
            HtmlTextWriter htmWrite = new HtmlTextWriter(strWrite);
            HtmlForm htmfrm = new HtmlForm();
            gvLogNotice.Parent.Controls.Add(htmfrm);
            htmfrm.Attributes["runat"] = "server";
            htmfrm.Controls.Add(gvLogNotice);
            htmfrm.RenderControl(htmWrite);
            Response.Write(strWrite.ToString());
            Response.Flush();
            Response.End();
        }
        catch (Exception ex) { }
}

我能不能得到一些关于我在这里失踪的帮助?先感谢您。

5 个答案:

答案 0 :(得分:1)

在导出按钮上尝试此代码:

 protected void btnExport_Click(object sender, EventArgs e)
{
    Response.Clear();
    Response.Buffer = true;
    Response.AddHeader("content-disposition", "attachment;filename=GridViewExport.xls");
    Response.Charset = "";
    Response.ContentType = "application/vnd.ms-excel";
    using (StringWriter sw = new StringWriter())
    {
        HtmlTextWriter hw = new HtmlTextWriter(sw);

        //To Export all pages
        GridView1.AllowPaging = false;
        GridViewBind();

        GridView1.HeaderRow.BackColor = Color.White;
        foreach (TableCell cell in GridView1.HeaderRow.Cells)
        {
            cell.BackColor = GridView1.HeaderStyle.BackColor;
        }
        foreach (GridViewRow row in GridView1.Rows)
        {
            row.BackColor = Color.White;
            foreach (TableCell cell in row.Cells)
            {
                if (row.RowIndex % 2 == 0)
                {
                    cell.BackColor = GridView1.AlternatingRowStyle.BackColor;
                }
                else
                {
                    cell.BackColor = GridView1.RowStyle.BackColor;
                }
                cell.CssClass = "textmode";
            }
        }

        GridView1.RenderControl(hw);

        //style to format numbers to string
        string style = @"<style> .textmode { } </style>";
        Response.Write(style);
        Response.Output.Write(sw.ToString());
        Response.Flush();
        Response.End();
    }
}
public override void VerifyRenderingInServerForm(Control control)
{
    /* Verifies that the control is rendered */
}

答案 1 :(得分:0)

答案 2 :(得分:0)

试试这个

protected void Button2_Click(object sender, EventArgs e)
    {
        Response.Clear();
        Response.Buffer = true;
        Response.AddHeader("content-disposition",
        "attachment;filename=GridViewExport.xls");
        Response.Charset = "";
        Response.ContentType = "application/vnd.xls";
        StringWriter sw = new StringWriter();
        HtmlTextWriter hw = new HtmlTextWriter(sw);
        GridView1.AllowPaging = false;
        GridView1.DataBind();
        GridView1.RenderControl(hw);
        string style = @"<style> .textmode { mso-number-format:\@; } </style>";
        Response.Write(style);
        Response.Output.Write(sw.ToString());
        Response.Flush();
        Response.End();
    }

答案 3 :(得分:0)

 private void ExportToExcel(DataTable dt)
        {
            Response.Clear();
            Response.Buffer = true;
            Response.AddHeader("content-disposition", "attachment;filename=Sheet1.xls");
            Response.Charset = "";
            Response.ContentType = "application/vnd.ms-excel";
            GridView dgGrid = new GridView();
            using (StringWriter sw = new StringWriter())
            {
                HtmlTextWriter hw = new HtmlTextWriter(sw);


                dgGrid.DataSource = dt;
                dgGrid.DataBind();

                dgGrid.HeaderRow.BackColor = Color.White;
                foreach (TableCell cell in dgGrid.HeaderRow.Cells)
                {
                    cell.BackColor = dgGrid.HeaderStyle.BackColor;
                }
                foreach (GridViewRow row in dgGrid.Rows)
                {
                    row.BackColor = Color.White;
                    foreach (TableCell cell in row.Cells)
                    {
                        if (row.RowIndex % 2 == 0)
                        {
                            cell.BackColor = dgGrid.AlternatingRowStyle.BackColor;
                        }
                        else
                        {
                            cell.BackColor = dgGrid.RowStyle.BackColor;
                        }
                        cell.CssClass = "textmode";
                    }
                }

                dgGrid.RenderControl(hw);

                //style to format numbers to string
                string style = @"<style> .textmode { mso-number-format:\@; } </style>";
                Response.Write(style);
                Response.Output.Write(sw.ToString());
                Response.Flush();
                Response.End();
            }
        }

答案 4 :(得分:0)

如果您的代码中没有 VerifyRenderingInServerForm ,就会发生这种情况。

只需将此代码段放在导出代码之后,它就会消失。

 public override void VerifyRenderingInServerForm(Control control)
    {
        /* Verifies that the control is rendered */
    }