c#.net导出为Excel文件

//如果不加此部分会报错误如:类型“GridView”的控件“GridView1”必须放在具有 runat=server 的窗体标记内。
        public override void VerifyRenderingInServerForm(Control control)
        {
            // Confirms that an HtmlForm control is rendered for  
        } 

        //方法
        protected void saveExcel(GridView gv)
        {
            string filename = "excel";
            Response.Clear();
            Response.Buffer = true;
            Response.Charset = "utf-8";
            Response.ContentType = "application/ms-excel";
            Response.ContentEncoding = System.Text.Encoding.GetEncoding("utf-8");
            Response.AddHeader("content-disposition", "attachment;filename=" + Server.UrlPathEncode(filename + ".xls"));
            //Response.AddHeader("content-disposition", "attachment;filename=FileName.xls");

            System.IO.StringWriter stringWrite = new System.IO.StringWriter();
            System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
            gv.RenderControl(htmlWrite);

            Response.Write(stringWrite.ToString());//在这里就是一个TABLE如:
1
2
3
Response.Flush(); Response.End(); }

你可能感兴趣的:(excel,string,server,table)