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#

相关阅读:

AspNet中WebFrom重写URL路径方法

字符串表达式计算 (使用DATATABLE)

C#反射Assembly.Load("程序集").CreateInstance("命名空间.类")

Unity 接口注入示例