2014年8月12日 星期二

ASP.NET GridView to Excel(GridView輸出到Excel)

ASP.NET GridView to Excel(GridView輸出到Excel)

C#:
protected void Page_Load(object sender, EventArgs e)
{
        DataTable dt = new DataTable();
        GridView1.DataSource = dt;
        GridView1.DataBind();

        #region HMTL Response
        Response.Clear();
        Response.Write("<meta http-equiv=Content-Type content=text/html;charset=utf-8>");
        Response.AddHeader("content-disposition", "attachment;filename=" + strExportFilename + ".xls");
        Response.Cache.SetCacheability(HttpCacheability.NoCache);
        Response.ContentType = "application/vnd.xls";
        //Response.Charset = "big5";  //utf-8
        Response.Charset = "utf-8";  //utf-8
        //Response.ContentEncoding = System.Text.Encoding.GetEncoding(950); //65001
        Response.ContentEncoding = System.Text.Encoding.GetEncoding(65001); //65001

        System.IO.StringWriter stringWrite = new System.IO.StringWriter();
        System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
        GridView1.RenderControl(htmlWrite); //將物件GridView1輸出
        //Table1.RenderControl(htmlWrite); //將物件Table1輸出
        Response.Write(stringWrite.ToString().Replace("<div>", "").Replace("</div>", ""));
        Response.End();
        #endregion
}

沒有留言:

張貼留言