[转]GridView导出Excel总结
GridView導(dǎo)出Excel方法
一、引用如下命名空間
using System.IO;
using System.Text;
二、詳細(xì)代碼
方法一:將代碼直接寫在頁面
??? /// <summary>
??? /// 數(shù)據(jù)導(dǎo)出
??? /// </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();
??? }
方法二、將以上代碼改進(jìn)成公共方法:
??? /// <summary>
??? /// 將網(wǎng)格數(shù)據(jù)導(dǎo)出到Excel
??? /// </summary>
??? /// <param name="ctrl">網(wǎng)格名稱(如GridView1)</param>
??? /// <param name="FileType">要導(dǎo)出的文件類型(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();
??? }
三、注意事項(xiàng):
在導(dǎo)出的時(shí)候,如果某個(gè)字段為長數(shù)字(如身份證號碼511922198507151512)、以0開頭的編號(如0809111212)之類的數(shù)據(jù)。如果不加處理在導(dǎo)出的Excel文件中將會(huì)被分別當(dāng)作5.11922E+17和809111212來處理,這樣與我們要達(dá)到 的實(shí)際效果不一致。所以我們要加以處理,即給單元格數(shù)據(jù)規(guī)定格式。常見的格式如下:
1) 文本:vnd.ms-excel.numberformat:@
2) 日期:vnd.ms-excel.numberformat:yyyy/mm/dd
3) 數(shù)字:vnd.ms-excel.numberformat:#,##0.00
4) 貨幣:vnd.ms-excel.numberformat:¥#,##0.00
5) 百分比:vnd.ms-excel.numberformat: #0.00%
使用方法如下:
//給第一個(gè)單元格設(shè)置格式為
e.Item.Cells[0].Attributes.Add("style","vnd.ms-excel.numberformat:@");
//給第四個(gè)單元格設(shè)置格式為
e.Item.Cells[3].Attributes.Add("style","vnd.ms-excel.numberformat:¥#,###.00");
本文來自CSDN博客,轉(zhuǎn)載請標(biāo)明出處:http://blog.csdn.net/suchgoingdown/archive/2009/03/10/3977013.aspx
轉(zhuǎn)載于:https://www.cnblogs.com/itzsl/archive/2010/02/21/1670163.html
總結(jié)
以上是生活随笔為你收集整理的[转]GridView导出Excel总结的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 开源云计算平台 abiCloud
- 下一篇: Remoting方面的转帖1