如何将GridView数据导出到Excel

语言:ASP.net

平台:带有ASP.net的Visual Studio 2008

技术:用于ASP.net

介绍

1.将gridview添加到aspx文件中

2.在aspx文件中添加一个按钮,并将名称命名为“ btnExportToExcel”

3.在aspx.cs文件中编写代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
namespace ExampleOnAjax
{
    public partial class ExportFiles : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            DataTable dtRecords = new DataTable();
            dtRecords.Columns.Add("State", typeof(string));
            dtRecords.Columns.Add("City", typeof(string));
            DataRow dr = dtRecords.NewRow();
            dr["State"] = "Karnataka";
            dr["City"] = "Bangalore";
            dtRecords.Rows.Add(dr); 
            grdData.DataSource = dtRecords;
            grdData.DataBind();
        } 
        protected void btnExportToExcel_Click(object sender, EventArgs e)
        {
            Response.Clear();
            Response.ContentType = "application/ms-excel";
            Response.Charset ="";
            Page.EnableViewState = false;
            Response.AddHeader("Content-Disposition", "inline;filename=report.xls");
            System.IO.StringWriter tw = new System.IO.StringWriter();
            System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(tw);
            grdData.RenderControl(hw);
            Response.Write(tw.ToString());
            Response.End();
        }
        public override void VerifyRenderingInServerForm(Control control)
        { 
        }  
    }
}
摘要:

运行应用程序,单击按钮,它将要求保存或打开文件,如果保存,它将保存到磁盘中

或者,如果单击“打开”,则直接打开excel文件。

From: https://bytes.com/topic/net/insights/912685-how-export-gridview-data-excel

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值