GridView轉出Excel (Word, Txt)

摘要:GridView轉出Excel (Word, Txt)

最近負責的專案剛好有遇到要將GridView輸出成office檔案給行政人員使用.
所以就去Google了一下網路上的文章.
參考一些大大們的文章
 
protected void btnExcel1_Click(object sender, EventArgs e)
{
    ExcelExport(ref gvProgress);
}
 
//Export the Excel.  傳入要輸出的GridView
protected void ExcelExport(ref GridView gv)
    {
        Response.Clear();
        Response.AddHeader("content-disposition", "attachment;filename=PoolExport.xls");
        Response.ContentType = "application/vnd.xls";
        System.IO.StringWriter sw = new System.IO.StringWriter();
        System.Web.UI.HtmlTextWriter htw = new HtmlTextWriter(sw);
 
        //關閉換頁跟排序   
        gv.AllowSorting = false;
        gv.AllowPaging = false;
 
        //移去不要的欄位    如新增修改刪除 IUD
        //gvProgress.Columns.RemoveAt(GridView1.Columns.Count - 1);  //最後一欄
        gv.Columns.RemoveAt(0);  //第一欄
        gv.DataBind() //若有自訂的Bind Function則要使用自訂的Bind() , 否則會無法輸出GridView的資料(空白或打叉叉)
 
        //建立暫存HtmlForm避免以下錯誤   
        //Control 'GridView1' of type 'GridView' must be placed inside    
        //a form tag with runat=server.    
        //另一種做法是override VerifyRenderingInServerForm後不做任何事   
        //這樣就可以直接GridView1.RenderControl(htw);     //gv.RenderControl(htw);
        //public override void VerifyRenderingInServerForm(Control control){}   或者覆寫此方法,則不用建立暫存Form.
 
        HtmlForm hf = new HtmlForm();
        Controls.Add(hf);
        hf.Controls.Add(gv);
        hf.RenderControl(htw);      
        Response.Write(sw.ToString());
        Response.End();
}
 
 
//For Word
//更改MIME的型態即可
Response.AddHeader("content-disposition", "attachment;filename=test.doc"); //word檔名  
Response.ContentType = "application/vnd.ms-word";
 
//For Txt 
//更改MIME的型態
Response.AddHeader("content-disposition", "attachment;filename=test.txt"); //txt檔名  
Response.ContentType = "application/vnd.ms-word"; 
 
//因Txt檔輸出後沒有排版,可建立StringBuilder將GridView的資料進行排版
System.Text.StringBuilder sb = new System.Text.StringBuilder(); 
//建立迴圈將全部資料跑過一次且輸入sb中
//最後Response.Write
Response.Write(sb.ToString()); 
 
若有錯誤請多多指教~共勉之. 
 
參考文章:
 
 

努力學習dot Net , 若有錯誤請多多指教 ^^