GridView導出Excel

  protected void ExportToExcel(string FileType, string FileName)
    {
        Response.Clear();
        Response.Charset = "GB2312";
        Response.ContentEncoding = System.Text.Encoding.UTF8;
        Response.HeaderEncoding = System.Text.Encoding.Default;
        Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(FileName, Encoding.UTF8).ToString());
        Response.ContentType = FileType;
        StringWriter tw = new StringWriter();
        HtmlTextWriter htw = new HtmlTextWriter(tw);
        GridView1.AllowPaging = false;
        Bind();
        GridView1.RenderControl(htw);
        Response.Write(tw.ToString());
        Response.End();
        GridView1.AllowPaging = true;
        Bind();
    }
 protected void txt_Out_Click(object sender, EventArgs e)
    {
        if (GridView1.Rows.Count < 1)
        {
            Response.Write("<script>alert('沒有資料')</script>");
            return;
        }

        ExportToExcel("application/ms-excel", "Data.xls");
    }

 

posted @ 2013-03-11 19:51  sirili  阅读(119)  评论(0编辑  收藏  举报