reading excel fetching date in general format

喜你入骨 提交于 2019-12-11 19:37:58

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/12858310/reading-excel-fetching-date-in-general-format

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!