(Visual Studio 2010) How To Export DataGridView Data To Excel In C# Windows Application – Microsoft Excel 2010
(Visual Studio 2010) How To Export DataGridView Data To Excel In C# Windows Application – Microsoft Excel 2010

The following program demonstrates How To Export DataGridView Data To Excel In C# Windows Application. I am using Visual Studio 2010 and Microsoft Excel 2010. DataGridView is populated from static data. No database connection is required in this tutorial. The DataGridView data is exported to Excel file when you click export button on C# windows form application.

Table of Contents:
- Adding reference to microsoft.office.interop.excel
- Getting all the Header columns from datagrid.
- Getting all normal Rows Apart from Header column from datagrid.
- Saving DataGridView Header as first row And other Rows as normal, To Excel file.
To Add reference (microsoft.office.interop.excel) to your project follow the following steps:
Step 1. Right-click on “References” and select “Add Reference”.

Step 2. Select the “.NET” tab.

Step 3. Look for Microsoft Office.Interop.Excel.

Source Code
_Application excelApp; _Workbook excelWorkbook; _Worksheet excelWorksheet; try { excelApp = new Microsoft.Office.Interop.Excel.Application(); excelWorkbook = excelApp.Workbooks.Add(Type.Missing); excelWorksheet = null; excelWorksheet = excelWorkbook.Sheets["Sheet1"]; excelWorksheet = excelWorkbook.ActiveSheet; //Excel Sheet Name excelWorksheet.Name = "ExportDataGridViewToExcel"; //Get DatagridView Header for (int i = 1; i < dataGridView1.Columns.Count; i++) { //Populating excel Header excelWorksheet.Cells[1, i] = dataGridView1.Columns[i - 1].HeaderText; } //Export DatagridView Rows for (int j = 0; j < dataGridView1.RowCount; j++) { for (int k = 0; k < dataGridView1.ColumnCount - 1; k++) { //Populating Excel Rows excelWorksheet.Cells[j + 2, k + 1] = dataGridView1.Rows[j].Cells[k].Value.ToString(); } } SaveFileDialog exportExcelFile = new SaveFileDialog(); //Excel File Name exportExcelFile.FileName = "exportedExcelFile"; //Default Excel Extension exportExcelFile.DefaultExt = "xlsx"; if (exportExcelFile.ShowDialog() == DialogResult.OK) { //Saving Excel File To your Computer excelWorkbook.SaveAs(exportExcelFile.FileName, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, XlSaveAsAccessMode.xlNoChange , Type.Missing, Type.Missing, Type.Missing, Type.Missing); //Message after excel file is saved MessageBox.Show("Excel File Saved"); } } catch (Exception ex) { MessageBox.Show(ex.Message); }
