Search code examples
c#.netexceldatetimeoledb

reading excel fetching date in general format


In the application we have a wizard with multiple tabs. On the first tab we can select a excel sheet path using a browse button. The moment you select the excel, excel file contents are loaded in a dataset (everything in correct format including DATE fields). Then click Next to go to the next wizard tab.

But if the file is open program loads the excel and this time with all the date fields in General format. eg: 6/22/2006 as 38890

We are trying to find if the excel is open or being used by another format as:

    bool IsFilebeingUsed(FileInfo file)
    {
        FileStream stream = null;

        try
        {
            stream = file.Open(FileMode.Open, FileAccess.Read, FileShare.None);
        }
        catch (IOException)
        {
            return true;
        }
        finally
        {
            if (stream != null)
                stream.Close();
        }
        return false;
    }

The way we are trying to read the excel is as follows:

string sql = string.Format("SELECT * FROM [{0}]", excelSheetName);
internal OleDbCommand command = new OleDbCommand();
command.CommandText = sql;
OleDbDataReader oleRdr = command.ExecuteReader();

DataTable dataTable = new DataTable();
datatable.TableName = excelSheetName;
dataTable.Load(oleRdr);

Can anyone tell whats wrong with the application or code?


Solution

  • More updated question can be found here.

    So I solved the issue in a unsatisfactory way. I noticed with my analysis and experiments and ultimately concluded that when the excel is open in MS-Excel and we try reading the excel in C# using OleDbDataReader, some of the DataTypes are not read properly and unfortunately DateTime being one of them in my case.

    As a solution, at present we are forcing the user to close the excel at the time we are reading the excel file. I even noticed that if the excel is open in Read-only mode in MS-Excel, then the data read is correct for all DataTypes including DateTime. But when opened in Write-Mode, then data read is incorrect.

    These are my analysis results and I know/agree that the results are a bit weird. If any one disagree or have something else in their mind, then let me know and please correct me.