将gridview数据导出到CSV文件 [英] Export gridview data into CSV file

查看:729
本文介绍了将gridview数据导出到CSV文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个gridview控件在ASP.Net 2.0和我需要导出这个gridview数据到CSV文件。

I have a gridview control in ASP.Net 2.0 and i need to export this gridview data into CSV file.

我已经绑定这个gridview与dataset.After绑定数据集到gridview我已经做了一些变化gridview数据,如果我在数据集中的0,然后我在gridview中显示0为开始,如果我在数据集中有1,然后我显示为未开始在gridview中。

I have bind this gridview with the dataset.After binding the dataset to the gridview i have done some changes in the gridview data like if I got 0 in dataset then i show 0 as "Started" in the gridview and if i got 1 in the dataset then I show 1 as "Not Started" in the gridview.

所以,我不能直接使用数据集导出。我需要的是我想要的代码(在c#中)将我的gridview数据(不是数据集的数据)导出到CSV文件。

So, i can't use dataset directly for exporting. What i need is..i want the code (in c#) that export my gridview data(not dataset's data) into CSV file.

推荐答案

尝试下面的代码,我已经使用了很多次。它会将数据直接从gridview导出到代码中指定的csv文件。

Try following code, i used it already many times. It will export the data directly from gridview to csv file specified in the code.

protected void btnExportCSV_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;
    GridView1.DataBind();

    StringBuilder sb = new StringBuilder();
    for (int k = 0; k < GridView1.Columns.Count; k++)
    {
        //add separator
        sb.Append(GridView1.Columns[k].HeaderText + ',');
    }
    //append new line
    sb.Append("\r\n");
    for (int i = 0; i < GridView1.Rows.Count; i++)
    {
        for (int k = 0; k < GridView1.Columns.Count; k++)
        {
            //add separator
            sb.Append(GridView1.Rows[i].Cells[k].Text + ',');
        }
        //append new line
        sb.Append("\r\n");
    }
    Response.Output.Write(sb.ToString());
    Response.Flush();
    Response.End();
}

有关详情,请访问这里
希望它会帮助你

for more information visit Here Hope it will help you

这篇关于将gridview数据导出到CSV文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆