将gridview导出为任何格式

时间:2014-04-28 10:56:16

标签: c# export-to-excel

我正在尝试将gridview导出为ex​​cel / pdf / word格式

我添加了所有必要的实现,但它仍然给我一个错误,例如"控制类型' gridview'必须放在带有runat = server"

的表单标记内

请查看下面的代码,

.aspx页面

<%@ Page Title="" Language="C#" MasterPageFile="~/MasterPages/OrganizationMaster.Master" EnableEventValidation="false" AutoEventWireup="true" CodeBehind="SearchInvoice.aspx.cs" Inherits="Site.pages.ContactStaff.ViewInvoice" %>

.aspx.cs页面

  public override void VerifyRenderingInServerForm(Control control)
    {
        /* Confirms that an HtmlForm control is rendered for the specified ASP.NET
           server control at run time. */
    }

.ascx.cs control

 protected void btnExport_Click(object sender, EventArgs e)
    {
        if (ddlExport.SelectedIndex != 0)
        {
              if (ddlExport.SelectedValue == "Word")
            {
                Response.AddHeader("content-disposition", "attachment;filename=OtherCourses.doc");
                Response.Cache.SetCacheability(HttpCacheability.NoCache);
                Response.ContentType = "application/vnd.word";

                StringWriter stringWrite = new StringWriter();
                HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
                List<InvoiceHelper> invoicelist = svc.RetriveInvoiceList(Request.Url);
                grdinvoicelist.AllowPaging = false;
                grdinvoicelist.DataSource = invoicelist;
                grdinvoicelist.DataBind();
                grdinvoicelist.RenderControl(htmlWrite);

                Response.Write(stringWrite.ToString());
                Response.End();
            }
        }
    }

1 个答案:

答案 0 :(得分:0)

你可能遇到和我一样的问题。

在您的MasterPage中,您已经有一个表单标记, 当您在网络表单中执行第二个表单标记时。

尝试尽可能使用最干净的母版页,例如:

<%@ Master Language="C#" AutoEventWireup="true" CodeBehind="TotalEmpty.master.cs" 

Inherits="ProjectName.MasterPages.TotalEmpty" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <asp:ContentPlaceHolder ID="head" runat="server">
    </asp:ContentPlaceHolder>
</head>
<body>
    <div>
        <asp:ContentPlaceHolder ID="ContentPlaceHolder1" runat="server">

        </asp:ContentPlaceHolder>
    </div>
</body>
</html>