How To Export Datagridview To Excel In C Sharp

How To Export Datagridview To Excel In C#

How To Export Datagridview To Excel In C#
How To Export Datagridview To Excel In C#
How To Export Datagridview To Excel In C#
How To Export Datagridview To Excel In C#
How To Export Datagridview To Excel In C#

This Tutorial Shows How To Export Datagridview To Excel In C# .Net Windows Application Using Visual Studio 2010 And Microsoft Excel 2010.
Datagridview Column Headers are exported to the first excel row and other rows from the second Datagridview row.
To use excel classes you need to import/add microsoft.office.interop.excel library to your project.
Datagridview rows are populated manually , and they contain static data. Image column is the last one and it’s not exported to excel. Only the path is exported.

Form1.cs SOURCE CODE

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Microsoft.Office.Interop.Excel;

namespace HowToExportDataGridViewToExcelInCSharp
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            Image dataGridViewImage1 = Image.FromFile("C:/Users/Public/Pictures/Sample Pictures/Chrysanthemum.jpg");
            exportExcelTodataGridView1.Rows.Add("Naomi Jacob", "JacobNaomi@emailextenxion.com", "+1999999999", "English", "United States Of America", "Female", "C:/Users/Public/Pictures/Sample Pictures/Chrysanthemum.jpg", dataGridViewImage1);
            Image dataGridViewImage2 = Image.FromFile("C:/Users/Public/Pictures/Sample Pictures/Chrysanthemum.jpg");
            exportExcelTodataGridView1.Rows.Add("Naomi Jacob", "JacobNaomi@emailextenxion.com", "+1999999999", "English", "United States Of America", "Female", "C:/Users/Public/Pictures/Sample Pictures/Chrysanthemum.jpg", dataGridViewImage1);
            Image dataGridViewImage3 = Image.FromFile("C:/Users/Public/Pictures/Sample Pictures/Chrysanthemum.jpg");
            exportExcelTodataGridView1.Rows.Add("Naomi Jacob", "JacobNaomi@emailextenxion.com", "+1999999999", "English", "United States Of America", "Female", "C:/Users/Public/Pictures/Sample Pictures/Chrysanthemum.jpg", dataGridViewImage1);
            Image dataGridViewImage4 = Image.FromFile("C:/Users/Public/Pictures/Sample Pictures/Chrysanthemum.jpg");
            exportExcelTodataGridView1.Rows.Add("Naomi Jacob", "JacobNaomi@emailextenxion.com", "+1999999999", "English", "United States Of America", "Female", "C:/Users/Public/Pictures/Sample Pictures/Chrysanthemum.jpg", dataGridViewImage1);
            Image dataGridViewImage5 = Image.FromFile("C:/Users/Public/Pictures/Sample Pictures/Chrysanthemum.jpg");
            exportExcelTodataGridView1.Rows.Add("Naomi Jacob", "JacobNaomi@emailextenxion.com", "+1999999999", "English", "United States Of America", "Female", "C:/Users/Public/Pictures/Sample Pictures/Chrysanthemum.jpg", dataGridViewImage1);
            Image dataGridViewImage6 = Image.FromFile("C:/Users/Public/Pictures/Sample Pictures/Chrysanthemum.jpg");
            exportExcelTodataGridView1.Rows.Add("Naomi Jacob", "JacobNaomi@emailextenxion.com", "+1999999999", "English", "United States Of America", "Female", "C:/Users/Public/Pictures/Sample Pictures/Chrysanthemum.jpg", dataGridViewImage1);
            Image dataGridViewImage7 = Image.FromFile("C:/Users/Public/Pictures/Sample Pictures/Tulips.jpg");
            exportExcelTodataGridView1.Rows.Add("Naomi Jacob", "JacobNaomi@emailextenxion.com", "+1999999999", "English", "United States Of America", "Female", "C:/Users/Public/Pictures/Sample Pictures/Tulips.jpg", dataGridViewImage7);

        }

        private void btnExportDataGridViewToExcel_Click(object sender, EventArgs e)
        {
            _Application ExportDataGridViewToExcelInCSharpApp;
            _Workbook ExportDataGridViewToExcelInCSharpWorkBook;
            _Worksheet ExportDataGridViewToExcelInCSharpWorkSheet = null;


            try
            {
                ExportDataGridViewToExcelInCSharpApp = new Microsoft.Office.Interop.Excel.Application();
                ExportDataGridViewToExcelInCSharpWorkBook = ExportDataGridViewToExcelInCSharpApp.Workbooks.Add(Type.Missing);
                ExportDataGridViewToExcelInCSharpWorkSheet = ExportDataGridViewToExcelInCSharpWorkBook.Sheets["Sheet1"];
                ExportDataGridViewToExcelInCSharpWorkSheet = ExportDataGridViewToExcelInCSharpWorkBook.ActiveSheet;
                ExportDataGridViewToExcelInCSharpWorkSheet.Name = "ExportedDataFromDataGridView";

                for (int dataGridViewColumnIndex = 1; dataGridViewColumnIndex < exportExcelTodataGridView1.Columns.Count; dataGridViewColumnIndex++)
                {
                    ExportDataGridViewToExcelInCSharpWorkSheet.Cells[1, dataGridViewColumnIndex] = exportExcelTodataGridView1.Columns[dataGridViewColumnIndex - 1].HeaderText;
                }

                for (int datagridviewrowsindex = 0; datagridviewrowsindex < exportExcelTodataGridView1.Rows.Count; datagridviewrowsindex++)
                {
                    for (int datagridviewcolumnsindex = 0; datagridviewcolumnsindex < exportExcelTodataGridView1.Columns.Count - 1; datagridviewcolumnsindex++)
                    {
                        ExportDataGridViewToExcelInCSharpWorkSheet.Cells[datagridviewrowsindex + 2, datagridviewcolumnsindex + 1] = exportExcelTodataGridView1.Rows[datagridviewrowsindex].Cells[datagridviewcolumnsindex].Value.ToString();
                    }
                }

                SaveFileDialog exportDataGridViewToExcelInCSharpSaveDialog = new SaveFileDialog();
                //exportDataGridViewToExcelInCSharpSaveDialog.InitialDirectory = "C:/Users/Authentic/Desktop";
                exportDataGridViewToExcelInCSharpSaveDialog.DefaultExt = "xlsx";
                exportDataGridViewToExcelInCSharpSaveDialog.FileName = "ExportDataGridViewToExcelFile";
                exportDataGridViewToExcelInCSharpSaveDialog.Title = "Save Excel File";                
                exportDataGridViewToExcelInCSharpSaveDialog.Filter = "Excel Files | *.xls;*.xlsx;*.xlm";
                if (exportDataGridViewToExcelInCSharpSaveDialog.ShowDialog() == DialogResult.OK)
                {
                    ExportDataGridViewToExcelInCSharpWorkBook.SaveAs(exportDataGridViewToExcelInCSharpSaveDialog.FileName, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, XlSaveAsAccessMode.xlNoChange, Type.Missing, Type.Missing, Type.Missing,  Type.Missing);
                }


                ExportDataGridViewToExcelInCSharpWorkBook.Close();
                ExportDataGridViewToExcelInCSharpApp.Quit();


            }
            catch (Exception ExportDataGridViewToExcelInCSharException)
            {
                MessageBox.Show("Error " + ExportDataGridViewToExcelInCSharException.Message);
            }
            finally
            { 
            
            }
        }
    }
}

Form1.Designer.cs SOURCE CODE

namespace HowToExportDataGridViewToExcelInCSharp
{
    partial class Form1
    {
        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows Form Designer generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.exportExcelTodataGridView1 = new System.Windows.Forms.DataGridView();
            this.btnExportDataGridViewToExcel = new System.Windows.Forms.Button();
            this.Column1 = new System.Windows.Forms.DataGridViewTextBoxColumn();
            this.Column2 = new System.Windows.Forms.DataGridViewTextBoxColumn();
            this.Column3 = new System.Windows.Forms.DataGridViewTextBoxColumn();
            this.Column4 = new System.Windows.Forms.DataGridViewTextBoxColumn();
            this.Column5 = new System.Windows.Forms.DataGridViewTextBoxColumn();
            this.Column6 = new System.Windows.Forms.DataGridViewTextBoxColumn();
            this.Column7 = new System.Windows.Forms.DataGridViewTextBoxColumn();
            this.Column8 = new System.Windows.Forms.DataGridViewImageColumn();
            ((System.ComponentModel.ISupportInitialize)(this.exportExcelTodataGridView1)).BeginInit();
            this.SuspendLayout();
            // 
            // exportExcelTodataGridView1
            // 
            this.exportExcelTodataGridView1.AllowUserToAddRows = false;
            this.exportExcelTodataGridView1.AutoSizeColumnsMode = System.Windows.Forms.DataGridViewAutoSizeColumnsMode.Fill;
            this.exportExcelTodataGridView1.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
            this.exportExcelTodataGridView1.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] {
            this.Column1,
            this.Column2,
            this.Column3,
            this.Column4,
            this.Column5,
            this.Column6,
            this.Column7,
            this.Column8});
            this.exportExcelTodataGridView1.Location = new System.Drawing.Point(1, 2);
            this.exportExcelTodataGridView1.Name = "exportExcelTodataGridView1";
            this.exportExcelTodataGridView1.Size = new System.Drawing.Size(772, 285);
            this.exportExcelTodataGridView1.TabIndex = 0;
            // 
            // btnExportDataGridViewToExcel
            // 
            this.btnExportDataGridViewToExcel.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.btnExportDataGridViewToExcel.Location = new System.Drawing.Point(472, 292);
            this.btnExportDataGridViewToExcel.Name = "btnExportDataGridViewToExcel";
            this.btnExportDataGridViewToExcel.Size = new System.Drawing.Size(301, 25);
            this.btnExportDataGridViewToExcel.TabIndex = 1;
            this.btnExportDataGridViewToExcel.Text = "Export DataGridView To Excel";
            this.btnExportDataGridViewToExcel.UseVisualStyleBackColor = true;
            this.btnExportDataGridViewToExcel.Click += new System.EventHandler(this.btnExportDataGridViewToExcel_Click);
            // 
            // Column1
            // 
            this.Column1.HeaderText = "Full Name";
            this.Column1.Name = "Column1";
            // 
            // Column2
            // 
            this.Column2.HeaderText = "Email";
            this.Column2.Name = "Column2";
            // 
            // Column3
            // 
            this.Column3.HeaderText = "Phone Number";
            this.Column3.Name = "Column3";
            // 
            // Column4
            // 
            this.Column4.HeaderText = "Language";
            this.Column4.Name = "Column4";
            // 
            // Column5
            // 
            this.Column5.HeaderText = "Country";
            this.Column5.Name = "Column5";
            // 
            // Column6
            // 
            this.Column6.HeaderText = "Gender";
            this.Column6.Name = "Column6";
            // 
            // Column7
            // 
            this.Column7.HeaderText = "Image Path";
            this.Column7.Name = "Column7";
            // 
            // Column8
            // 
            this.Column8.HeaderText = "Image";
            this.Column8.ImageLayout = System.Windows.Forms.DataGridViewImageCellLayout.Stretch;
            this.Column8.Name = "Column8";
            this.Column8.Resizable = System.Windows.Forms.DataGridViewTriState.True;
            this.Column8.SortMode = System.Windows.Forms.DataGridViewColumnSortMode.Automatic;
            // 
            // Form1
            // 
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(778, 320);
            this.Controls.Add(this.btnExportDataGridViewToExcel);
            this.Controls.Add(this.exportExcelTodataGridView1);
            this.Name = "Form1";
            this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
            this.Text = "Form1";
            this.Load += new System.EventHandler(this.Form1_Load);
            ((System.ComponentModel.ISupportInitialize)(this.exportExcelTodataGridView1)).EndInit();
            this.ResumeLayout(false);

        }

        #endregion

        private System.Windows.Forms.DataGridView exportExcelTodataGridView1;
        private System.Windows.Forms.Button btnExportDataGridViewToExcel;
        private System.Windows.Forms.DataGridViewTextBoxColumn Column1;
        private System.Windows.Forms.DataGridViewTextBoxColumn Column2;
        private System.Windows.Forms.DataGridViewTextBoxColumn Column3;
        private System.Windows.Forms.DataGridViewTextBoxColumn Column4;
        private System.Windows.Forms.DataGridViewTextBoxColumn Column5;
        private System.Windows.Forms.DataGridViewTextBoxColumn Column6;
        private System.Windows.Forms.DataGridViewTextBoxColumn Column7;
        private System.Windows.Forms.DataGridViewImageColumn Column8;
    }
}


Program.cs SOURCE CODE

using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;

namespace HowToExportDataGridViewToExcelInCSharp
{
    static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new Form1());
        }
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *