2015年6月10日 星期三

ASP.NET GridView匯出Excel並解決亂碼問題

ASP.NET 將GridView內的資料匯出成Excel檔
---
看了上面這篇後,總算解決了問題點
如code:重點在這一行了!!
Response.Write("<meta http-equiv=Content-Type content=text/html;charset=utf-8>");
using System; 
using System.Data; 
using System.Configuration; 
using System.Collections; 
using System.Web; 
using System.Web.Security; 
using System.Web.UI; 
using System.Web.UI.WebControls; 
using System.Web.UI.WebControls.WebParts; 
using System.Web.UI.HtmlControls; 
 
public partial class _Default : System.Web.UI.Page  
{ 
    protected void Button2_Click(object sender, EventArgs e) 
    { 
        Response.ClearContent(); 
        Response.Write("<meta http-equiv=Content-Type content=text/html;charset=utf-8>"); 
        string excelFileName = "測試Excel檔案.xls"; 
        Response.AddHeader("content-disposition", "attachment;filename=" + Server.UrlEncode(excelFileName)); 
        Response.ContentType = "application/excel"; 
        System.IO.StringWriter stringWrite = new System.IO.StringWriter(); 
        System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite); 
        GridView1.RenderControl(htmlWrite); 
        Response.Write(stringWrite.ToString()); 
        Response.End(); 
    } 
 
    public override void VerifyRenderingInServerForm(Control control)    
    { 
        // '處理'GridView' 的控制項 'GridView' 必須置於有 runat=server 的表單標記之中   
    }    
}

沒有留言:

張貼留言