Export DataGridView into .csv file

Following example I am trying to save the DataGridView's Data into .csv file

Please create a Windows Application and Add a DataGridView and a button on Form1, and please use following code.

I have explained code inline


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;

namespace DataGridView_ExportToCSV
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void Form1_Load(object sender, EventArgs e)
{
//Fetch the Employee details
SqlDataAdapter sqlDa = new SqlDataAdapter("Select EmployeeID, firstname," +
"Lastname from Employees",
"Server=localhost;Database=Northwind;Trusted_Connection=True;");
DataSet ds = new DataSet();
//Fill the DataSet
sqlDa.Fill(ds, "Employees");
//Set the DataSource of DataGrid View
dataGridView1.DataSource = ds.Tables[0];
}

private void button1_Click(object sender, EventArgs e)
{
string strExport = "";
//Loop through all the columns in DataGridView to Set the
//Column Heading
foreach (DataGridViewColumn dc in dataGridView1.Columns)
{
strExport += dc.Name + " ";
}
strExport = strExport.Substring(0, strExport.Length - 3) + Environment.NewLine.ToString();
//Loop through all the row and append the value with 3 spaces
foreach (DataGridViewRow dr in dataGridView1.Rows)
{
foreach (DataGridViewCell dc in dr.Cells)
{
if (dc.Value != null)
{
strExport += dc.Value.ToString() + " ";
}
}
strExport += Environment.NewLine.ToString();
}
strExport = strExport.Substring(0, strExport.Length - 3) + Environment.NewLine.ToString();
//Create a TextWrite object to write to file, select a file name with .csv extention
System.IO.TextWriter tw = new System.IO.StreamWriter("data.csv");
//Write the Text to file
tw.Write(strExport);
//Close the Textwrite
tw.Close();
}
}
}


Please find attached source code.

Hope this helps.


Cheers
SatishKumar J
Microsoft MVP(ASP.NET)


Attachments

  • Source Code (28359-11533-DataGridView_ExportToCSV.zip)
  • Comments

    Guest Author: Ali Danish06 Mar 2012

    Thanks a lot, i was searching last two days for exporting Datagridview to excel and csv. finally i got right solution.
    your article is so clear. It working properly.

    Guest Author: lynx29 Jun 2012

    thank you