Read from excel and insert into data table in c#


using System.Data.OleDb;
using System.IO;
 
private DataTable ReadExcelToTable(string path)
{
        //Connection String
        string extenstion = Path.GetExtension(path);
        string connstring = "";
        if (extenstion == "xls" || extenstion == "XLS")
        {
            connstring = "Provider=Microsoft.JET.OLEDB.4.0;Data Source=" + path + ";Extended Properties='Excel 8.0;HDR=NO;IMEX=1';";
        }
        else
        {
            connstring = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Extended Properties='Excel 8.0;HDR=NO;IMEX=1';";
        }
        //connstring = "Provider=Microsoft.JET.OLEDB.4.0;Data Source=" + path + ";Extended Properties='Excel 8.0;HDR=NO;IMEX=1';";
         
        using (OleDbConnection conn = new OleDbConnection(connstring))
        {
            DataSet set = new DataSet();
            try
            {
                conn.Open();
                //Get All Sheets Name
                DataTable sheetsName = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "Table" });

                //Get the First Sheet Name
                string firstSheetName = sheetsName.Rows[0]["TABLE_NAME"].ToString();

                //Query String
                string sql = string.Format("SELECT * FROM [{0}]", firstSheetName);
                OleDbDataAdapter ada = new OleDbDataAdapter(sql, connstring);

                ada.Fill(set);
            }
            catch (Exception ex)
            {
                MessageBox.Show("File Loading Error, Try again \n" + ex.Message);
                return null;
            }
            return set.Tables[0];
        }
}

Comments

Popular posts from this blog

Provision AWS EC2 Instance and RDS with Terraform, and Deploy Spring Boot App to EC2 Instance via GitHub Action Pipeline

JQuery UI Autocomplete, custom HTML structure for result?

Easy Ui Jquery easyui-textbox change onChange event