[转]GridView导出Excel总结
GridView導出Excel方法
一、引用如下命名空間
using System.IO;
using System.Text;
二、詳細代碼
方法一:將代碼直接寫在頁面
??? /// <summary>
??? /// 數據導出
??? /// </summary>
??? /// <param name="FileType"></param>
??? /// <param name="FileName"></param>
??? private void Export(string FileType, string FileName)
??? {
??????? Response.Charset = "GB2312";
??????? Response.ContentEncoding = System.Text.Encoding.UTF8;//注意編碼
??????? Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(FileName, Encoding.UTF8).ToString());
??????? Response.ContentType = FileType;
??????? this.EnableViewState = false;
??????? StringWriter tw = new StringWriter();
??????? HtmlTextWriter hw = new HtmlTextWriter(tw);
??????? gridGatewayDetails.RenderControl(hw);
??????? Response.Write(tw.ToString());
??????? Response.End();
??? }
方法二、將以上代碼改進成公共方法:
??? /// <summary>
??? /// 將網格數據導出到Excel
??? /// </summary>
??? /// <param name="ctrl">網格名稱(如GridView1)</param>
??? /// <param name="FileType">要導出的文件類型(Excel:application/ms-excel)</param>
??? /// <param name="FileName">要保存的文件名</param>
??? public static void GridViewToExcel(Control ctrl, string FileType, string FileName)
??? {
??????? HttpContext.Current.Response.Charset = "GB2312";
??????? HttpContext.Current.Response.ContentEncoding = Encoding.UTF8;//注意編碼
??????? HttpContext.Current.Response.AppendHeader("Content-Disposition",
??????????? "attachment;filename=" + HttpUtility.UrlEncode(FileName, Encoding.UTF8).ToString());
??????? HttpContext.Current.Response.ContentType = FileType;//image/JPEG;text/HTML;image/GIF;vnd.ms-excel/msword
??????? ctrl.Page.EnableViewState = false;
??????? StringWriter tw = new StringWriter();
??????? HtmlTextWriter hw = new HtmlTextWriter(tw);
??????? ctrl.RenderControl(hw);
??????? HttpContext.Current.Response.Write(tw.ToString());
??????? HttpContext.Current.Response.End();
??? }
三、注意事項:
在導出的時候,如果某個字段為長數字(如身份證號碼511922198507151512)、以0開頭的編號(如0809111212)之類的數據。如果不加處理在導出的Excel文件中將會被分別當作5.11922E+17和809111212來處理,這樣與我們要達到 的實際效果不一致。所以我們要加以處理,即給單元格數據規定格式。常見的格式如下:
1) 文本:vnd.ms-excel.numberformat:@
2) 日期:vnd.ms-excel.numberformat:yyyy/mm/dd
3) 數字:vnd.ms-excel.numberformat:#,##0.00
4) 貨幣:vnd.ms-excel.numberformat:¥#,##0.00
5) 百分比:vnd.ms-excel.numberformat: #0.00%
使用方法如下:
//給第一個單元格設置格式為
e.Item.Cells[0].Attributes.Add("style","vnd.ms-excel.numberformat:@");
//給第四個單元格設置格式為
e.Item.Cells[3].Attributes.Add("style","vnd.ms-excel.numberformat:¥#,###.00");
本文來自CSDN博客,轉載請標明出處:http://blog.csdn.net/suchgoingdown/archive/2009/03/10/3977013.aspx
轉載于:https://www.cnblogs.com/itzsl/archive/2010/02/21/1670163.html
總結
以上是生活随笔為你收集整理的[转]GridView导出Excel总结的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 开源云计算平台 abiCloud
- 下一篇: Remoting方面的转帖1