C#DataTable 导出到Excel的几种方式

文章介绍了如何将DataTable数据导出为Excel文件的两种方法:一种是适用于Web的字符流导出,通过Http响应直接输出;另一种是客户端方法,包括以CSV格式导出和使用Microsoft.Office.Interop.Excel库创建Excel文件。这两种方法都处理了特殊字符的转义问题。
摘要由CSDN通过智能技术生成

将DataTable导出是常见的需求,可以调用以下几种类方法进行导出。

1.适用于web的字符流导出方式

private static void DataTableToExcel(DataTable dt, string saveName)
        {
            DataGrid dgExcel = new DataGrid();
            dgExcel.DataSource = dt;
            dgExcel.DataBind();

            HttpContext.Current.Response.Charset = "GB2312";
            string fileName = HttpUtility.UrlEncode(saveName, System.Text.Encoding.UTF8);
            string str = "attachment;filename=" + fileName + ".xls";
            HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.UTF8;
            HttpContext.Current.Response.ContentType = "application/ms-excel";
            HttpContext.Current.Response.AppendHeader("content-disposition", str);

            //如需添加其他标头或新增自定义行

            //StringWriter sw_title = new StringWriter();
            //HtmlTextWriter htmlTextWriter_title = new HtmlTextWriter(sw_title);
            //htmlTextWriter_title.AddStyleAttribute(HtmlTextWriterStyle.FontSize, "20px");//样式
            //Label label1 = new Label();
            //label1.Text = "在原有DataDable上新增标头    自定义行";
            //label1.RenderControl(htmlTextWriter_title);

        

            StringWriter sw = new StringWriter();
            HtmlTextWriter htmTextWriter = new HtmlTextWriter(sw);
            dgExcel.RenderControl(htmTextWriter);
            HttpContext.Current.Response.Write("<meta http-equiv=\"content-type\" content=\"application/vnd.ms-excel; charset=utf-8\"/>" + sw.ToString());

            HttpContext.Curren

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值