Read Excel Data in csharp

You can get excel sheet data in c# by two methods one is by opening connection and 2nd is by using interop.

In this post I am describing the method 1 by opening connections

METHOD I

        public static DataTable GetExcelData(string _path)
        {
            DataTable ExcelData = new DataTable();
            string ConnectionString = @”Provider=Microsoft.ACE.OLEDB.12.0;Data Source=” + _path + “;Extended Properties=’Excel 12.0 Xml;HDR=YES’;”;


            using (OleDbConnection con = new OleDbConnection(ConnectionString))
            {
                if (con.State == ConnectionState.Closed)
                {
                    con.Open();


                    using (OleDbCommand cm = new OleDbCommand(“SELECT * FROM [Sheet1$]”, con))
                    {
                        using (OleDbDataAdapter DA = new OleDbDataAdapter(cm))
                        {
                            DA.Fill(ExcelData);
                        }
                    }
                }
            }




            return ExcelData;
        }