Read Excel file using OLEDB Data Provider in C# .Net


  //Read To Excel 97-2003 File
    private Boolean ImportExcel(String strFilePath)
    {
        if (!File.Exists(strFilePath)) return false;
        String strExcelConn = "Provider=Microsoft.Jet.OLEDB.4.0;"
        + "Data Source=" + strFilePath + ";"
        + "Extended Properties='Excel 8.0;HDR=Yes'";
        OleDbConnection connExcel = new OleDbConnection(strExcelConn);
        OleDbCommand cmdExcel = new OleDbCommand();
        try
        {
            cmdExcel.Connection = connExcel;

        //Check if the Sheet Exists
        connExcel.Open();
        DataTable dtExcelSchema;
        //Get the Schema of the WorkBook
        dtExcelSchema = connExcel.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
        connExcel.Close();

        //Read Data from Sheet1
        connExcel.Open();
        OleDbDataAdapter da = new OleDbDataAdapter();
        DataSet ds = new DataSet();
        string SheetName = dtExcelSchema.Rows[0]["TABLE_NAME"].ToString();
        cmdExcel.CommandText = "SELECT * From [" + SheetName + "]";
        //Range Query
        //cmdExcel.CommandText = "SELECT * From [" + SheetName + "A3:B5]";

        da.SelectCommand = cmdExcel;
        da.Fill(ds);
        connExcel.Close();
        return true;
    }
    catch
    {
        return false;
    }
    finally
    {
        cmdExcel.Dispose();
        connExcel.Dispose();
    }
}
//Read To Excel 97-2007 File
private Boolean ImportExcel2007(String strFilePath)
{
    if (!File.Exists(strFilePath)) return false;
    String strExcelConn = "Provider=Microsoft.ACE.OLEDB.12.0;"
    + "Data Source=" + strFilePath + ";"
    + "Extended Properties='Excel 8.0;HDR=No'";
    OleDbConnection connExcel = new OleDbConnection(strExcelConn);
    OleDbCommand cmdExcel = new OleDbCommand();
    try
    {
        cmdExcel.Connection = connExcel;

        //Check if the Sheet Exists
        connExcel.Open();
        DataTable dtExcelSchema;
        //Get the Schema of the WorkBook
        dtExcelSchema = connExcel.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
        connExcel.Close();

        //Read Data from Sheet1
        connExcel.Open();
        OleDbDataAdapter da = new OleDbDataAdapter();
        DataSet ds = new DataSet();
        string SheetName = dtExcelSchema.Rows[0]["TABLE_NAME"].ToString();
        cmdExcel.CommandText = "SELECT * From [" + SheetName + "]";

        //Range Query
        //cmdExcel.CommandText = "SELECT * From [" + SheetName + "A3:B5]";

        da.SelectCommand = cmdExcel;
        da.Fill(ds);
        connExcel.Close();
        return true;
    }
    catch
    {
        return false;
    }
    finally
    {
        cmdExcel.Dispose();
        connExcel.Dispose();
    }
}