将 gridview 数据导出到 CSV 文件 [英] Export gridview data into CSV file
问题描述
我在 ASP.Net 2.0 中有一个 gridview 控件,我需要将此 gridview 数据导出到 CSV 文件中.
I have a gridview control in ASP.Net 2.0 and i need to export this gridview data into CSV file.
我已将此 gridview 与数据集绑定.将数据集绑定到 gridview 后,我对 gridview 数据进行了一些更改,例如如果我在数据集中得到 0,那么我在 gridview 中将 0 显示为已开始",如果我得到了1 在数据集中,然后我在 gridview 中将 1 显示为未开始".
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.
所以,我不能直接使用数据集进行导出.我需要的是..我想要将我的 gridview 数据(不是数据集的数据)导出到 CSV 文件的代码(在 c# 中).
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("
");
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("
");
}
Response.Output.Write(sb.ToString());
Response.Flush();
Response.End();
}
欲了解更多信息,请访问 这里希望能帮到你
for more information visit Here Hope it will help you
这篇关于将 gridview 数据导出到 CSV 文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!