Monday, June 24, 2013

Export Datatable to Excel in C#

First, add the "Microsoft.Office.Interop.Excel" assembly reference in your project. Please make sure your project uses .Net Framework 4.0

Microsoft.Office.Interop.Excel.Application ExcelApp =
            new Microsoft.Office.Interop.Excel.Application();
            ExcelApp.Application.Workbooks.Add(Type.Missing);

            // Change properties of the Workbook 

            ExcelApp.Columns.ColumnWidth = 20;

            // Storing header part in Excel
            for (int i = 1; i < dataGridView1.Columns.Count + 1; i++)
            {
                ExcelApp.Cells[1, i] = dataGridView1.Columns[i - 1].HeaderText;
            }

            // Storing Each row and column value to excel sheet
            for (int i = 0; i < dataGridView1.Rows.Count - 1; i++)
            {
                for (int j = 0; j < dataGridView1.Columns.Count; j++)
                {
                    ExcelApp.Cells[i + 2, j + 1] = dataGridView1.Rows[i].Cells[j].Value.ToString();
                }
            }
            MessageBox.Show("Excel file created , you can find the file D:\\Employee Data.xlsx");
            ExcelApp.Visible = true;
            ExcelApp.ActiveWorkbook.SaveCopyAs("D:\\Employee Data.xlsx");
 ExcelApp.ActiveWorkbook.Saved = true;
 Marshal.FinalReleaseComObject(ExcelApp);

Enjoy..