您现在的位置: 365建站网 > 365学习 > GridView数据导入到Excel表中

GridView数据导入到Excel表中

文章来源:365jz.com     点击数:715    更新时间:2009-09-18 10:25   参与评论

(1)StringWriter 不能用,因为没有引入命名空间System.IO

(2)Encoding不能用,因为没有引入命名空间System.Text

(3)在用户控件上使用的GridView不能重写VerifyRenderingInServerForm函数。

 

一、GridView数据导出到Excel文件中

protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                GridView1.DataSource = getDataSet();
                GridView1.DataBind();
            }
        }

        //filename为Excel的名字,ToExcelGrid就是数据源,在此为DataView数据源;
        private void ExportExcelFromDataGrid(string filename, System.Web.UI.WebControls.GridView ToExcelGrid)
        {
            Response.Clear();
            Response.Buffer = true;
            Response.Charset = "utf-8";
            Response.AppendHeader("Content-Disposition", "attachment;filename=" + Server.UrlEncode(filename));
            Response.ContentEncoding = System.Text.Encoding.GetEncoding("utf-8");//设置输出流为简体中文  
            Response.ContentType = "application/ms-excel";//设置输出文件类型为excel文件。    

            this.EnableViewState = false;
            System.Globalization.CultureInfo myCItrad = new System.Globalization.CultureInfo("ZH-CN", true);
            System.IO.StringWriter oStringWriter = new System.IO.StringWriter(myCItrad);
            System.Web.UI.HTMLTextWriter oHtmlTextWriter = new System.Web.UI.HtmlTextWriter(oStringWriter);
            ToExcelGrid.RenderControl(oHtmlTextWriter);
            Response.Write(oStringWriter.ToString());
            Response.End();
        }

        //如果没有下面方法会报错类型“GridView”的控件“GridView1”必须放在具有 runat=server 的窗体标记内ITPUB个人空间 cB6w"i'J/n

        public override void VerifyRenderingInServerForm(Control control)
        {
            // Confirms that an HtmlForm control is rendered for
            //里边不写任何的东西
        }
 protected void btnWrite_Click(object sender, EventArgs e)
        {
            ExportExcelFromDataGrid("TestExcel.xls", this.GridView1);
        }

}  

如对本文有疑问,请提交到交流论坛,广大热心网友会为你解答!! 点击进入论坛


发表评论 (715人查看0条评论)
请自觉遵守互联网相关的政策法规,严禁发布色情、暴力、反动的言论。
用户名: 验证码: 点击我更换图片
最新评论
------分隔线----------------------------