从gridview中导入excel

第一步,给页面上的gridview赋数据源,然后调用下面方法

public void outExcel()
        {
            string name = returnName();

            string style = @"<style>.text{mso-number-format:\@;}</style>";

            Response.ClearContent();

            Response.Buffer = true;
            Response.Charset = "gb2312";
            Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");

            Response.AddHeader("content-disposition", "attachment; filename=" + System.Web.HttpUtility.UrlEncode(name, System.Text.Encoding.UTF8) + ".xls");

            Response.ContentType = "application/excel";

            StringWriter sw = new StringWriter();

            HtmlTextWriter htw = new HtmlTextWriter(sw);

            GridView1.RenderControl(htw);

            Response.Write(style);

            Response.Write(sw.ToString());

            Response.End();
        }

posted @ 2010-11-04 15:51  凌鸢  阅读(318)  评论(0编辑  收藏  举报