C#导出数据到Excel通用的方法类
2015-11-26 11:36
531 查看
导出数据到Excel通用的方法类,请应对需求自行修改。
资源下载列表
using System.Data; using System.IO; namespace IM.Common.Tools { public class Export { public string Encoding = "UTF-8"; System.Web.HttpResponse response = System.Web.HttpContext.Current.Response; public void EcportExcel(DataTable dt, string fileName) { if (dt != null) { StringWriter sw = new StringWriter(); CreateStringWriter(dt, ref sw); sw.Close(); response.Clear(); response.Buffer = true; response.Charset = Encoding; //this.EnableViewState = false; response.AddHeader("Content-Disposition", "attachment; filename=" + fileName + ".xls"); response.ContentType = "application/ms-excel"; //response.ContentEncoding = System.Text.Encoding.GetEncoding(Encoding) response.ContentEncoding = System.Text.Encoding.UTF8; response.Write(sw); response.End(); } } private void CreateStringWriter(DataTable dt, ref StringWriter sw) { string sheetName = "sheetName"; sw.WriteLine("<html xmlns:x=\"urn:schemas-microsoft-com:office:excel\">"); sw.WriteLine("<head>"); sw.WriteLine("<!--[if gte mso 9]>"); sw.WriteLine("<xml>"); sw.WriteLine(" <x:ExcelWorkbook>"); sw.WriteLine(" <x:ExcelWorksheets>"); sw.WriteLine(" <x:ExcelWorksheet>"); sw.WriteLine(" <x:Name>" + sheetName + "</x:Name>"); sw.WriteLine(" <x:WorksheetOptions>"); sw.WriteLine(" <x:Print>"); sw.WriteLine(" <x:ValidPrinterInfo />"); sw.WriteLine(" </x:Print>"); sw.WriteLine(" </x:WorksheetOptions>"); sw.WriteLine(" </x:ExcelWorksheet>"); sw.WriteLine(" </x:ExcelWorksheets>"); sw.WriteLine("</x:ExcelWorkbook>"); sw.WriteLine("</xml>"); sw.WriteLine("<![endif]-->"); sw.WriteLine("</head>"); sw.WriteLine("<body>"); sw.WriteLine("<table>"); sw.WriteLine(" <tr>"); string[] columnArr = new string[dt.Columns.Count]; int i = 0; foreach (DataColumn columns in dt.Columns) { sw.WriteLine(" <td>" + columns.ColumnName + "</td>"); columnArr[i] = columns.ColumnName; i++; } sw.WriteLine(" </tr>"); foreach (DataRow dr in dt.Rows) { sw.WriteLine(" <tr>"); foreach (string columnName in columnArr) { sw.WriteLine(" <td style='vnd.ms-excel.numberformat:@'>" + dr[columnName] + "</td>"); } sw.WriteLine(" </tr>"); } sw.WriteLine("</table>"); sw.WriteLine("</body>"); sw.WriteLine("</html>"); } } }
相关文章推荐
- C# repeater控件序号绑定
- C#文件夹路径获得
- C#中虚方法,抽象类(方法)和接口的区别
- C# 属性和字段的区别
- 【术】深入理解c#反射
- (转)C# Enum,Int,String的互相转换 枚举转换
- [转]C#取得内网IP、外网IP、客户端IP方法
- Windows Server 2008 部署webservice(C# .Net)
- 【C#】Event事件的应用之观察者模式
- 【C#】匿名方法的终结者——Lambda表达式
- 【术】c#中利用反射实现深拷贝
- C#中通过Selenium IWebDriver实现人人网相册备份工具
- C# FTP 上传 下载(汇总)
- C# FTP 上传 下载(汇总)
- WPF中C#代码触发鼠标点击事件
- C# 上传下载ftp(支持断点续传)
- C# 上传下载ftp(支持断点续传)
- csharp: 百度语音合成
- c#后台常用知识
- c#实现动态加载Dll