SIGN UP MEMBER LOGIN:    
ARTICLE

Import Data from Excel to DataGridView in C#

Posted by Ankur Gupta Articles | Learn .NET July 20, 2010
In this article you will learn how to import Data from Excel to DataGridView in C#.
Reader Level:
Download Files:
 

First need to add the reference "Microsoft ADO Ext. 2.8". You can easily add it from COM components.

Add an open Dialog box control on form

Form1.JPG

Put the following code on Browser button click events…..

        private void button1_Click_1(object sender, EventArgs e)

        {

            OpenFileDialog fdlg = new OpenFileDialog();

            fdlg.Title = "Select file";

            fdlg.InitialDirectory = @"c:\";

            fdlg.FileName = txtFileName.Text;

            fdlg.Filter = "Excel Sheet(*.xls)|*.xls|All Files(*.*)|*.*";

            fdlg.FilterIndex = 1;

            fdlg.RestoreDirectory = true;

            if (fdlg.ShowDialog() == DialogResult.OK)

            {

                txtFileName.Text = fdlg.FileName;

                Import();

                Application.DoEvents();

            }

        }


This will filter only Excel file from your Machine.

This Excel file can contains more than one Sheet. You need to add another form to all excel sheets name so that user can select any one excel sheet which he want to import.

Write the following code on Page Load even of this form

        private void Select_Tables_Load(object sender, EventArgs e)

        {

            if (!DataTables)

            {

                if (Tables != null)

                {

                    for (int tables = 0; tables < Tables.Length; tables++)

                    {

                        try

                        {

                            ListViewItem lv = new ListViewItem();

                            lv.Text = Tables[tables].ToString();

                            lv.Tag = tables;

                            lstViewTables.Items.Add(lv);

                        }

                        catch (Exception ex)

                        { }

                    }

                }

            }

            else

            {

                if (dtTable.Rows.Count>0)

                {

                    for (int tables = 0; tables < dtTable.Rows.Count; tables++)

                    {

                        try

                        {

                            ListViewItem lv = new ListViewItem();

                            lv.Text = dtTable.Rows[tables][0].ToString();

                            lv.Tag = dtTable.Rows[tables][0];

                            lstViewTables.Items.Add(lv);

                        }

                        catch (Exception ex)

                        { }

                    }

                }

            }

        }
 

By the following function we can find the total sheets in Excel file.

        public static string[] GetTableExcel(string strFileName)

        {

            string[] strTables = new string[100];

            Catalog oCatlog = new Catalog();

            ADOX.Table oTable = new ADOX.Table();

            ADODB.Connection oConn = new ADODB.Connection();

            oConn.Open("Provider=Microsoft.Jet.OleDb.4.0; Data Source = " + strFileName + "; Extended Properties = \"Excel 8.0;HDR=Yes;IMEX=1\";", "", "", 0);

            oCatlog.ActiveConnection = oConn;

            if (oCatlog.Tables.Count > 0)

            {

                int item = 0;

                foreach (ADOX.Table tab in oCatlog.Tables)

                {

                    if (tab.Type == "TABLE")

                    {

                        strTables[item] = tab.Name;

                        item++;

                    }

                }

            }

            return strTables;

        }

 
Form2.JPG

Following function return a dataset so that you can bind it from Data Grid View  easily.

        public static DataTable GetDataTableExcel(string strFileName, string Table)

        {

            System.Data.OleDb.OleDbConnection conn = new System.Data.OleDb.OleDbConnection("Provider=Microsoft.Jet.OleDb.4.0; Data Source = " + strFileName + "; Extended Properties = \"Excel 8.0;HDR=Yes;IMEX=1\";");

            conn.Open();

            string strQuery = "SELECT * FROM [" + Table + "]";

            System.Data.OleDb.OleDbDataAdapter adapter = new System.Data.OleDb.OleDbDataAdapter(strQuery, conn);

            System.Data.DataSet ds = new System.Data.DataSet();

            adapter.Fill(ds);

            return ds.Tables[0];

        }

 

 Form3.JPG

To see the complete source code you can download the zip file.

erver'>
Login to add your contents and source code to this article
share this article :
post comment
 

Thanks

Posted by Ankur Gupta May 08, 2012

Nice one really awesome

Posted by znaneswar kodavanti May 07, 2012

I already added the reference "Microsoft ADO Ext. 2.8". But it still doesn't work...

Posted by das mier Apr 22, 2012

Thanks a lot..... Nice Coding and Simple.....

Posted by Nandu R Mar 25, 2012

Thanks it works fine!

Posted by Shuky Feb 02, 2012
Team Foundation Server Hosting
Become a Sponsor
PREMIUM SPONSORS
  • Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
    ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications. Visit DynamicPDF here
6 Months Free & No Setup Fees ASP.NET Hosting!
Become a Sponsor