如何将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

你可能感兴趣的:(如何将GridView数据导出到CSV)