2009-04-15 [.NET C#] 將GridView的資料轉存成Excel形式 7615 0 .Net C# 2009-04-16 摘要:[C#] 將GridView的資料轉存成Excel形式 這是很久以前寫過的功能,筆記筆記,近來發現記性越來越不好。這個funtion一定要寫不能無法轉存public override void VerifyRenderingInServerForm(Control control) { } 以下為Button Click事件protected void ExpBtn_Click(object sender, EventArgs e) { //設定轉存Excel之檔名: 預設為四碼年兩碼月兩碼日兩碼時兩碼分兩碼秒(以現在時間為準) string FileName = DateTime.Now.Year + DateTime.Now.Month + DateTime.Now.Day + DateTime.Now.Hour + DateTime.Now.Minute + DateTime.Now.Secend; //抓取資料庫資料並轉成DataView() Data.DataView dv = ExportManager.getEmployeeLevelExport(2); this.GridView1.DataSource = dv; //預設不允許分頁() GridView1.AllowPaging = false; //預設不允許排序() GridView1.AllowSorting = false; //預設底圖顏色為白色() GridView1.BackColor = System.Drawing.Color.White; GridView1.DataBind(); Response.Clear(); Response.Buffer = true; Response.AddHeader("content-disposition", "attachment; filename=" + FileName + ".xls"); Response.ContentType = "application/vnd.ms-excel"; this.EnableViewState = false; System.IO.StringWriter oStringWriter = new System.IO.StringWriter(); System.Web.UI.HtmlTextWriter oHtmlTextWriter = new System.Web.UI.HtmlTextWriter(oStringWriter); //預設編碼為(utf - 8) Response.Write("<html><head><meta http-equiv=Content-Type content=\"text/html; charset=utf-8\">"); GridView1.RenderControl(oHtmlTextWriter); //預設全為文字格式() Response.Write("<style>td{mso-number-format:\\@}</style>"); Response.Write(oStringWriter.ToString()); Response.Write("</body></html>"); Response.End(); } ASP.NETC#ExcelGridView 回首頁