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.
- 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.