Export DataGridView Data To CSV In C#

In this code example, we will learn how to export DataGridView data to a CSV file and save it in a folder using C# code.
 
In this program, first, we have to connect to the database and fetch data from there. Then, we will show that data in Data Grid View like in the below image.

 
Let us go to the page load event, fetch employee data, and bind the Data GridView.
  1. private void FrmExport_Load(object sender, EventArgs e)  
  2. {  
  3.     SqlConnection sqlCon;  
  4.     string conString = null;  
  5.     string sqlQuery = null;  
  6.   
  7.     conString = "Data Source=.;Initial Catalog=DemoTest;Integrated Security=SSPI;";  
  8.     sqlCon = new SqlConnection(conString);  
  9.     sqlCon.Open();  
  10.     sqlQuery = "SELECT * FROM tblEmployee";  
  11.     SqlDataAdapter dscmd = new SqlDataAdapter(sqlQuery, sqlCon);  
  12.     DataTable dtData = new DataTable();  
  13.     dscmd.Fill(dtData);  
  14.     dataGridView1.DataSource = dtData;  

 Then, on the button click event handler, write the below code.
  1. private void btnCsv_Click(object sender, EventArgs e)  
  2. {  
  3.     if (dataGridView1.Rows.Count > 0)  
  4.     {  
  5.         SaveFileDialog sfd = new SaveFileDialog();  
  6.         sfd.Filter = "CSV (*.csv)|*.csv";  
  7.         sfd.FileName = "Output.csv";  
  8.         bool fileError = false;  
  9.         if (sfd.ShowDialog() == DialogResult.OK)  
  10.         {  
  11.             if (File.Exists(sfd.FileName))  
  12.             {  
  13.                 try  
  14.                 {  
  15.                     File.Delete(sfd.FileName);  
  16.                 }  
  17.                 catch (IOException ex)  
  18.                 {  
  19.                     fileError = true;  
  20.                     MessageBox.Show("It wasn't possible to write the data to the disk." + ex.Message);  
  21.                 }  
  22.             }  
  23.             if (!fileError)  
  24.             {  
  25.                 try  
  26.                 {  
  27.                     int columnCount = dataGridView1.Columns.Count;  
  28.                     string columnNames = "";  
  29.                     string[] outputCsv = new string[dataGridView1.Rows.Count + 1];  
  30.                     for (int i = 0; i < columnCount; i++)  
  31.                     {  
  32.                         columnNames += dataGridView1.Columns[i].HeaderText.ToString() + ",";  
  33.                     }  
  34.                     outputCsv[0] += columnNames;  
  35.                               
  36.                     for (int i = 1; (i - 1) < dataGridView1.Rows.Count; i++)  
  37.                     {  
  38.                         for (int j = 0; j < columnCount; j++)  
  39.                         {  
  40.                             outputCsv[i] += dataGridView1.Rows[i - 1].Cells[j].Value.ToString() + ",";  
  41.                         }  
  42.                     }  
  43.   
  44.                     File.WriteAllLines(sfd.FileName, outputCsv, Encoding.UTF8);  
  45.                     MessageBox.Show("Data Exported Successfully !!!""Info");  
  46.                 }  
  47.                 catch(Exception ex)  
  48.                 {  
  49.                     MessageBox.Show("Error :" + ex.Message);  
  50.                 }  
  51.             }  
  52.         }  
  53.     }  
  54.     else  
  55.     {  
  56.         MessageBox.Show("No Record To Export !!!""Info");  
  57.     }  

Now, run the application. When we click on the "Export To CSV" button, it will ask where to save the file. Put a file name and click on OK. It will generate a CSV file.

I hope this code will help all readers. Happy Coding.

Next Recommended Reading Export DataGridView Data To PDF In C#