夏雷

积极人生,努力加油!
[导入]GridView直接导入到Excel中

  #region 由GridView直接导入到Excel中
    /// <summary>
    /// 由GridView直接导入到Excel中
    /// </summary>
    /// <param name="ctl">空间</param>
    public void ToExcel(System.Web.UI.Control ctl)
    {
        string ls_id = System.DateTime.Now.Year.ToString() + System.DateTime.Now.Month.ToString() + System.DateTime.Now.Day.ToString() + System.DateTime.Now.Hour.ToString() + System.DateTime.Now.Minute.ToString() + System.DateTime.Now.Second.ToString();

        HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=" + ls_id + ".xls");
        HttpContext.Current.Response.Charset = "UTF-8";
        HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.Default;
        HttpContext.Current.Response.ContentType = "application/ms-excel";
        ctl.Page.EnableViewState = false;
        System.IO.StringWriter tw = new System.IO.StringWriter();
        System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(tw);
        ctl.RenderControl(hw);
        HttpContext.Current.Response.Write(tw.ToString());
        HttpContext.Current.Response.End();
    }
    /// <summary>
    /// this.GridView1.RenderControl(hw);
    /// </summary>
    public void ToExcel()
    {//取消注释可以是用
        //VerifyRenderingInServerForm(GridView1);
        //Response.ContentType = "application/vnd.ms-excel";
        //Response.Charset = "";
        //this.EnableViewState = false;
        //System.IO.StringWriter sw = new System.IO.StringWriter();
        //System.Web.UI.HtmlTextWriter hw = new HtmlTextWriter(sw);
        //this.GridView1.RenderControl(hw);
        //Response.Write(sw.ToString());
        //Response.End();
    }
    /// <summary>
    /// 把控件 加载到服务段运行
    /// </summary>
    /// <param name="control">什么都不用写</param>
    public override void VerifyRenderingInServerForm(Control control)
    {
        //base.VerifyRenderingInServerForm(control);  
    }
 #endregion


文章来源:http://xialei222.blog.163.com/blog/static/48046738200811902729460

posted on 2008-02-19 12:27  夏雷  阅读(177)  评论(0编辑  收藏  举报