把datatable中数据导入到excel中

本文介绍了一种使用ASP.NET将数据从DataTable导出到Excel的方法。通过DataGrid渲染和HTTP上下文响应来实现Excel文件的下载。适用于需要批量导出数据的应用场景。
Asp.net开发时经常用到的功能,导出数据到Excel表中保存
        /// <summary>
        
/// 把datatable导入到excel中
        
/// </summary>
        
/// <param name="dt">DataTable</param>
        
/// <param name="defaultFileName">默认保存文件名</param>

        public static void DataTableToExcel(DataTable dt, string defaultFileName)
        
{
            DataGrid dgd 
= new DataGrid();
            dgd.DataSource 
= dt.DefaultView;
            dgd.DataBind();

            
if (dgd.Items.Count == 0)
            
{
                
throw (new Exception("there is no data in dataTable"));
            }

            
else
            
{
                HttpContext.Current.Response.Clear();
                HttpContext.Current.Response.Buffer 
= true;
                HttpContext.Current.Response.Charset 
= "gb2312";
                HttpContext.Current.Response.AppendHeader(
"Content-Disposition""attachment;filename=" + defaultFileName);
                
//HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding("GBK");
                HttpContext.Current.Response.ContentEncoding = Encoding.UTF7;
                
//设置输出流为简体中文,试了GBK会出现乱码
                HttpContext.Current.Response.ContentType = "application/ms-excel";
                
//设置输出文件类型为excel文件。
                CultureInfo myCItrad = new CultureInfo("ZH-CN"true);
                StringWriter oStringWriter 
= new StringWriter(myCItrad);
                HtmlTextWriter oHtmlTextWriter 
= new HtmlTextWriter(oStringWriter);
                dgd.RenderControl(oHtmlTextWriter);
                HttpContext.Current.Response.Write(oStringWriter.ToString());
                HttpContext.Current.Response.End();
            }

        }
 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值