Reputation: 11687
Few days back I asked a question but could not find enough answers. I analyzed the problem a bit more and decided to create a new thread. If I should have not, let me know or close the question.
I have an OPEN excel file with a column in Date format with some values like 6/22/2006, 6/22/2006. I am trying to read the excel using OleDbDataReader. The code is like this:
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);
I am using the connection string as:
string connectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=c:\ExcelData\sample.xls;Extended Properties='Excel 8.0;HDR=No;IMEX=1'";
The problem is I am not able to read the date values in correct (DateTime
) format. I believe everything is treated as numeric format. So my result is
6/22/2006 as 38890
After reading some articles on internet, I understood my column is having multiple datatypes and then I changed my connection string as:
string connectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=c:\ExcelData\sample.xls;Extended Properties="Excel 8.0;HDR=No;IMEX=1;ImportMixedTypes=Text;TypeGuessRows=0"";
But still I am not able to read the excel in correct format. Any suggestions on this. It looks a weird problem to me. Please let me know if I to need to provide some more information.
Note: Also make a note that when my excel file is closed both the connection strings give me the correct data. Also for new doc formats.xlsx
we are using Microsoft.ACE.OLEDB.12.0
.
EDIT
I tried editing the registry as well....but no relief.
But when I changed the value IMEX = 0
or IMEX = 1
it is working fine again. Can any one tell the exactly what is happening?
EDIT 2
When I changed HDR=Yes
still everything worked good. Any help please? I could not find enough help on internet.
Upvotes: 1
Views: 1833
Reputation: 11687
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.
Upvotes: 2