asp.net C#将文档或控件dataGrid输出为Excel文档下载

本文介绍如何使用 ASP.NET 将网页上的 DataGrid 数据导出到 Excel 文件中,包括设置响应头、定义数据流及渲染控件的具体步骤。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

        private void Page_Load(object sender, System.EventArgs e)
        {
            DataSet ds = new DataSet();
            sqlDataAdapter1.Fill(ds);
            DataGrid1.DataSource = ds;
            DataGrid1.DataBind();
        }

---------------------------------
下载按钮代码如下:
        private void Button1_Click(object sender, System.EventArgs e)
        {
            //1.定义文档类型、字符编码
            Response.Clear();
          Response.Buffer= true;
          Response.Charset="utf-8";

            //attachment 参数表示作为附件下载,online在线打开
            //filename=FileFlow.xls 指定输出文件的名称,注意其扩展名和指定文件类型相符,可以为:.doc .xls .txt
            Response.AppendHeader("Content-Disposition","online;filename=FileFlow.xls");
            Response.ContentEncoding=System.Text.Encoding.GetEncoding("utf-8");

            //application/ms-excel, application/ms-word, application/ms-txt, application/ms-html
            Response.ContentType = "application/ms-excel";
            DataGrid1.EnableViewState = false;

            //2.定义一个输入流
            System.IO.StringWriter oStringWriter = new System.IO.StringWriter();
            System.Web.UI.HtmlTextWriter oHtmlTextWriter = new System.Web.UI.HtmlTextWriter(oStringWriter);

            //3.目标数据绑定到输入流输出
            this.RenderControl(oHtmlTextWriter);//this 表示输出本页,你也可以绑定datagrid,或其他支持obj.RenderControl()属性的控件
            Response.Write(oStringWriter.ToString());
            Response.End();
        }

=================================

        public void ExportExcel(DataTable dt, string fileName)
        {
            Response.AppendHeader("Content-Disposition", "attachment;filename=fileName.xls");
            Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
            Response.ContentType = "application/ms-excel";

            DataGrid dgExport = new DataGrid();
            dgExport.DataSource = dt;
            dgExport.DataBind();

            System.IO.StringWriter strWriter = new System.IO.StringWriter();
            HtmlTextWriter htmlWriter = new HtmlTextWriter(strWriter);
            dgExport.RenderControl(htmlWriter);
            Response.Clear();
            Response.Write(@"<meta http-equiv=""Content-Type"" content=""text/html; charset=gb2312"" />");
            Response.Write(strWriter.ToString());
            Response.End();
        }

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值