2013年12月12日 星期四

將資料匯出成excel檔案

這個方法是asp& asp.net都適用

1.要匯出的資料來源:

  (1)要匯出的資料是GridView,


  (2)要匯出的資料不是GridView
    將要匯出的資料組成html的<table>字串,包括字型大小、跨欄置中等。
    換行</br>時,你可能會需要用到這個語法<br style='mso-data-placement:same-cell;' />,達到換行的目的。
    UI -- 上放一個Panel, visible設為false,
       -- Panel裡面放一個Label,將html字串給Label.text



            this.Label3.Text = result;


            HttpContext.Current.Response.Clear();
            HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache);
            HttpContext.Current.Response.ContentType = "application/vnd.xls";

            //HttpContext.Current.Response.AddHeader("content-disposition", "attachment;filename=" + HttpUtility.UrlEncode("中文檔名", System.Text.Encoding.UTF8) + ".xls");     //解決中文檔名變成亂碼
            HttpContext.Current.Response.AddHeader("content-disposition", "attachment;filename=aa.xls");
            HttpContext.Current.Response.AddHeader("mata", "http-equiv=Content-Type content=text/html;charset=big5");

            System.IO.StringWriter sw = new System.IO.StringWriter();
            System.Web.UI.HtmlTextWriter htw = new System.Web.UI.HtmlTextWriter(sw);
            //this.Gridview1.RenderControl(htw);    //將Gridview匯出成excel
            this.Panel1.RenderControl(htw);         //將Panel匯出成excel



            HttpContext.Current.Response.Write(sw.ToString().Replace("<div>", "").Replace("</div>", ""));
            HttpContext.Current.Response.End();



完畢。

沒有留言:

張貼留言