C# NET DataTable导出Excel 并下载

 /// <summary>        
 /// DataTable中的数据导出到Excel并下载
 /// </summary>       
 /// <param name="fileName">Excel的文件名</param>
 /// <param name="dt">datatable数据表</param>       
 public void CreateExcel(string fileName,DataTable dt)       
 {     
    string FileName = Request.QueryString["tt"];       
    if (!string.IsNullOrEmpty(FileName))    
    {                    
    	Response.Clear();         
    	Response.Charset = "UTF-8";                
    	Response.Buffer = true;        
    	Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");                
    	Response.AppendHeader("Content-Disposition", "attachment;filename=\"" + System.Web.HttpUtility.UrlEncode(FileName, System.Text.Encoding.UTF8) + ".xls\"");
    	Response.ContentType = "application/ms-excel";                
    	string colHeaders = string.Empty;                
    	string ls_item = string.Empty;                
    	System.Data.DataRow[] myRow = dt.Select();                
    	int i = 0;                
    	int cl = dt.Columns.Count;                
    	foreach (System.Data.DataRow row in myRow)               
    	{                    
    		for (i = 0; i < cl; i++)           
    		{                        
    			if (i == (cl - 1))                       
    			{                            
    				ls_item += row[i].ToString() + "\n";
    			}                        
    			else                       
    			{                            
    				ls_item += row[i].ToString() + "\t";
    			}                    
    		}                    
    		Response.Output.Write(ls_item);                    
    		ls_item = string.Empty;                
    	}                
    	Response.Output.Flush();                
    	Response.End();       
     }        
}


转载请说明出处:原文链接 http://www.nbsite.cn/hdjs/138
标签: C#

相关阅读:

.NET 通过 Autofac 和 DynamicProxy 实现AOP

JS中URL编码与.net URL解码

ASP.NET Core 运行原理剖析:Startup

C# config配置文件之configSections配置及读取

json字符串转datatable使用Newtonsoft.Json不能将列"x”设置为空。请改用 DBNull 报错解决方法