Export DataGridView Data To Excel In C#

In this code example, we will learn how to export a DataGridView data to an Excel file and save to a folder using C# code.
 
In this program, first, we have connected to a database and fetched data from a database, and shown data in a DataGridView control something like this.
 
 
If you're new to DataGridView control, I recommend read this: DataGridView in C#
 
Before we go to the coding section, we must add Microsoft Excel object library reference to our project.
To do that right click on project and select Add Reference menu. After that go to COM tab and select and add Microsoft Excel 12.0 object library.

Project --> Add Reference --> COM tab --> Microsoft Excel 12.0 object library then press OK.

Now go to the page load event and fetch employee data and bind with the DataGridView.
  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;  

Now, on a Button click event handler, we have created an Excel object and document, get data from the DataGridView and add rows and columns to the document based on the data.
  1. private void btnExcel_Click(object sender, EventArgs e)  
  2. {  
  3.     if (dataGridView1.Rows.Count > 0)  
  4.     {  
  5.         SaveFileDialog sfd = new SaveFileDialog();  
  6.         sfd.Filter = "Excel (.xlsx)|  *.xlsx";  
  7.         sfd.FileName = "Output.xlsx";  
  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.                     Excel.Application XcelApp = new Excel.Application();  
  28.                     Excel._Workbook workbook = XcelApp.Workbooks.Add(Type.Missing);  
  29.                     Excel._Worksheet worksheet = null;  
  30.   
  31.                     worksheet = workbook.Sheets["Sheet1"];  
  32.                     worksheet = workbook.ActiveSheet;  
  33.                     worksheet.Name = "Output";  
  34.                     worksheet.Application.ActiveWindow.SplitRow = 1;  
  35.                     worksheet.Application.ActiveWindow.FreezePanes = true;  
  36.   
  37.                     for (int i = 1; i < dataGridView1.Columns.Count + 1; i++)  
  38.                     {  
  39.                         worksheet.Cells[1, i] = dataGridView1.Columns[i - 1].HeaderText;  
  40.                         worksheet.Cells[1, i].Font.NAME = "Calibri";  
  41.                         worksheet.Cells[1, i].Font.Bold = true;  
  42.                         worksheet.Cells[1, i].Interior.Color = Color.Wheat;  
  43.                         worksheet.Cells[1, i].Font.Size = 12;  
  44.                     }  
  45.   
  46.                     for (int i = 0; i < dataGridView1.Rows.Count; i++)  
  47.                     {  
  48.                         for (int j = 0; j < dataGridView1.Columns.Count; j++)  
  49.                         {  
  50.                             worksheet.Cells[i + 2, j + 1] = dataGridView1.Rows[i].Cells[j].Value.ToString();  
  51.                         }  
  52.                     }  
  53.   
  54.                     worksheet.Columns.AutoFit();  
  55.                     workbook.SaveAs(sfd.FileName);  
  56.                     XcelApp.Quit();  
  57.   
  58.                     ReleaseObject(worksheet);  
  59.                     ReleaseObject(workbook);  
  60.                     ReleaseObject(XcelApp);  
  61.   
  62.                     MessageBox.Show("Data Exported Successfully !!!""Info");  
  63.                 }  
  64.                 catch (Exception ex)  
  65.                 {  
  66.                     MessageBox.Show("Error :" + ex.Message);  
  67.                 }  
  68.             }  
  69.         }  
  70.     }  
  71.     else  
  72.     {  
  73.         MessageBox.Show("No Record To Export !!!""Info");  
  74.     }  
  75. }  
  76.   
  77. private void ReleaseObject(object obj)  
  78. {  
  79.     try  
  80.     {  
  81.         System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);  
  82.         obj = null;  
  83.     }  
  84.     catch (Exception ex)  
  85.     {  
  86.         obj = null;  
  87.         MessageBox.Show("Exception Occured while releasing object " + ex.Message, "Error");  
  88.     }  
  89.     finally  
  90.     {  
  91.         GC.Collect();  
  92.     }  

After creating the excel file, make sure to release the excel objects through ReleaseObject() method.

Now run the application and when we click on "Export To Excel" button, it will ask where to save the file. Put a file name and click on Ok and it will generate an excel file.

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