Analytics

2011年3月25日 星期五

[ASP.NET]使用 GridView 匯出完整EXCEL 解決Gridview分頁顯示不完全(Use Export GridView complete EXCEL solve Gridview Pagination incomplete)


問題
GridView 匯出完整EXCEL 解決Gridview分頁顯示不完全
當GridView有設定分頁的時候,會發生多頁的時候,EXCEL卻只會出某一頁,如下:
string attachment  = string.Format("attachment; filename=allocationInvoice{0}.xls" , DateTime.Now.ToString(("yyyyMMddHHmmss")));
Response.ClearContent();
Response.AddHeader("content-disposition", attachment);
Response.ContentType = "application/ms-excel";
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
GridView1.RenderControl(htw);
Response.Write(sw.ToString());
Response.End();




解決方法
解決方式其實很簡單,在respose到client前,重新指定GridView的PageSize就可以了!如下:
ReportViewPool.allocationInvoiceDataTable tb = DataLoad();//自訂義tb GridView1.DataSource = tb;
GridView1.PageSize = tb.Rows.Count;//重新指定頁面筆數
GridView1.DataBind();//指定以後依定要bind一次
string attachment = string.Format("attachment; filename=allocationInvoice{0}.xls" , DateTime.Now.ToString(("yyyyMMddHHmmss")));
Response.ClearContent();
Response.AddHeader("content-disposition", attachment);
Response.ContentType = "application/ms-excel";
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
GridView1.RenderControl(htw);
Response.Write(sw.ToString());
Response.End();

沒有留言:

熱門文章