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.
- private void FrmExport_Load(object sender, EventArgs e)
- {
- SqlConnection sqlCon;
- string conString = null;
- string sqlQuery = null;
- conString = "Data Source=.;Initial Catalog=DemoTest;Integrated Security=SSPI;";
- sqlCon = new SqlConnection(conString);
- sqlCon.Open();
- sqlQuery = "SELECT * FROM tblEmployee";
- SqlDataAdapter dscmd = new SqlDataAdapter(sqlQuery, sqlCon);
- DataTable dtData = new DataTable();
- dscmd.Fill(dtData);
- dataGridView1.DataSource = dtData;
- }
Then, on the button click event handler, write the below code.
- private void btnCsv_Click(object sender, EventArgs e)
- {
- if (dataGridView1.Rows.Count > 0)
- {
- SaveFileDialog sfd = new SaveFileDialog();
- sfd.Filter = "CSV (*.csv)|*.csv";
- sfd.FileName = "Output.csv";
- bool fileError = false;
- if (sfd.ShowDialog() == DialogResult.OK)
- {
- if (File.Exists(sfd.FileName))
- {
- try
- {
- File.Delete(sfd.FileName);
- }
- catch (IOException ex)
- {
- fileError = true;
- MessageBox.Show("It wasn't possible to write the data to the disk." + ex.Message);
- }
- }
- if (!fileError)
- {
- try
- {
- int columnCount = dataGridView1.Columns.Count;
- string columnNames = "";
- string[] outputCsv = new string[dataGridView1.Rows.Count + 1];
- for (int i = 0; i < columnCount; i++)
- {
- columnNames += dataGridView1.Columns[i].HeaderText.ToString() + ",";
- }
- outputCsv[0] += columnNames;
- for (int i = 1; (i - 1) < dataGridView1.Rows.Count; i++)
- {
- for (int j = 0; j < columnCount; j++)
- {
- outputCsv[i] += dataGridView1.Rows[i - 1].Cells[j].Value.ToString() + ",";
- }
- }
- File.WriteAllLines(sfd.FileName, outputCsv, Encoding.UTF8);
- MessageBox.Show("Data Exported Successfully !!!", "Info");
- }
- catch(Exception ex)
- {
- MessageBox.Show("Error :" + ex.Message);
- }
- }
- }
- }
- else
- {
- MessageBox.Show("No Record To Export !!!", "Info");
- }
- }
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.
I hope this code will help all readers. Happy Coding.

Ritesh DesalePosted Mar 23, 2022, 10:22 AM
If the cell value is blank or null then its throwing the Object referance error On line 40 use below convert instead of ToString to resolve the issue outputCsv[i] += Convert.ToString( dgvFinalData.Rows[i - 1].Cells[j].Value) + ",";
Andrew LiebenbergPosted Jan 13, 2021, 9:07 AM
With the code you have it ends up with a blank column at the end because of the forced delimiters at the end "ToString() + ","; " can you not export it without forcing the delimiter to be added on the last column header and last column rows
Carlos SotoPosted Nov 23, 2020, 1:40 PM
In line 36, change the (i-1) to just i: for (int i = 1; i <dataGridView1.Rows.Count; i++)
Daniel ChristiawanPosted Nov 12, 2020, 1:43 AM
I got error message when i try to export . it says "error ; object reference not set to an instance of an object"