How to export gridview data to CSV format in asp.net c#?

Posted by Prabu_Spark under ASP.NET on 12/7/2012 | Points: 10 | Views : 6956 | Status : [Member] | Replies : 3
Hi sir,
I want to export the gridview data to CSV format in asp.net C#.Kinly give
me the solution for this problem.

With regards,
J.Prabu.
[Email:prbspark@gmail.com]



Responses

Posted by: Megan00 on: 12/10/2012 [Member] Starter | Points: 25

Up
0
Down
Please look at this project: https://exportdata.codeplex.com/ , it can export data from database, command, listview to excel,pdf,word,html,xml,csv,text,dif,ms access etc. You can export datagridview to csv by below code:
private void btnLoad_Click(object sender, EventArgs e)

{
using (OleDbConnection oleDbConnection = new OleDbConnection())
{
oleDbConnection.ConnectionString = this.textBox1.Text;
OleDbCommand oleDbCommand = new OleDbCommand();
oleDbCommand.CommandText = this.textBox2.Text;
oleDbCommand.Connection = oleDbConnection;
using (OleDbDataAdapter da = new OleDbDataAdapter(oleDbCommand))
{
DataTable dt = new DataTable();
da.Fill(dt);
dataGridView1.DataSource = dt;
}
}
}
private void btnRUN_Click(object sender, EventArgs e)
{
TXTExport CSVExport = new TXTExport();
CSVExport.DataSource = Spire.DataExport.Common.ExportSource.DataTable;
CSVExport.DataTable = this.dataGridView1.DataSource as DataTable;
CSVExport.ActionAfterExport = Spire.DataExport.Common.ActionType.OpenView;
CSVExport.FileName = "CSV0721.csv";
CSVExport.SaveToFile();
}



Never give up! Smile to the world!
http://excelcsharp.blog.com/

Prabu_Spark, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: Ranjeet_8 on: 12/10/2012 [Member] [MVP] Gold | Points: 25

Up
0
Down
Refer this url
http://www.codeproject.com/Tips/477436/Export-Gridview-Data-to-Excel-in-ASP-NET

Prabu_Spark, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: Ranjeet_8 on: 12/10/2012 [Member] [MVP] Gold | Points: 25

Up
0
Down

using System.IO;

protected void btnExport_Click(object sender, EventArgs e)
{
ExportGridViewToCSV(GridView1, "myCSV");
}
public void ExportGridViewToCSV(GridView grdGridView, string fileName)
{
Response.Clear();
Response.AddHeader("content-disposition",string.Format
("attachment;filename={0}.csv",fileName));
Response.Charset = "";
Response.ContentType = "application/vnd.csv";
StringWriter stringWrite = new StringWriter();
HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
GridView1.RenderControl(htmlWrite);
Response.Write(stringWrite.ToString());
Response.End();
}
public override void VerifyRenderingInServerForm(Control control)
{
/* method must be implemented when using RenderControl */
}


Prabu_Spark, if this helps please login to Mark As Answer. | Alert Moderator

Login to post response