如何将GridView数据导出到CSV

语言:ASP.net

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

技术:用于ASP.net

级别:初学者

介绍

1.将gridview添加到aspx文件中

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

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 Example
{
    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 btnExportToCSV_Click(object sender, EventArgs e)
        {
             Response.Clear(); 
            Response.Buffer = true; 
            Response.AddHeader("content-disposition", "attachment;filename=GridViewExport.csv"); 
            Response.Charset = ""; 
            Response.ContentType = "application/text"; 
            GridView1.AllowPaging = false; 
            StringBuilder sb = new StringBuilder(); 
            for (int k = 0; k < GridView1.Columns.Count; k++)
            {
                sb.Append(GridView1.Columns[k].HeaderText + ',');
            } 
            sb.Append("\r\n");
            for (int i = 0; i < GridView1.Rows.Count; i++)
            { 
                for (int k = 0; k < GridView1.Columns.Count; k++)
                {
                    sb.Append(GridView1.Rows[i].Cells[k].Text + ',');
                } 
                sb.Append("\r\n");
            } 
            Response.Output.Write(sb.ToString()); 
            Response.Flush(); 
            Response.End();
        }
        public override void VerifyRenderingInServerForm(Control control)
        { 
        }  
    }
}
摘要:

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

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

参考文献

执照

From: https://bytes.com/topic/net/insights/912722-how-export-gridview-data-csv

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值