Home » excel » Query an Excel file with C#, issue with the numeric cells

Query an Excel file with C#, issue with the numeric cells

Posted by: admin April 23, 2020 Leave a comment

Questions:

I am querying an Excel file to retrieve data record and display them in a monitoring tool. The thing is that whenever I am trying to select a record with its id, with the following request, it throws an error when executing the query:

ExecuteCommandTextErrorHandling

telling me that the type in the query and the target cell are not compatible.

My request looks like

SELECT TOP 20 [Fields...] 
FROM [RECORD$] 
WHERE (([id] = '1'))

The id column can contains more than just numbers so its cell type is the default type which is standard.

My question is: how can I fetch the record without knowing its type before?

Do I have to enforce the column type, if so how? Do I have to catch the exception and retry without the quotes ?

Here is the code used to query the Excel file and my connection string

 public static DataTable queryXlsFile(String query, OleDbConnection dbConnection)
 {
        OleDbDataAdapter dbCommand = new OleDbDataAdapter(query, dbConnection);
        DataTable dt = new DataTable();
        dbCommand.Fill(dt);
        return dt;
    }

Provider=Microsoft.ACE.OLEDB.12.0; data source=C:\test\321.xls; Extended Properties=\"Excel 8.0;HDR=Yes;\";

Thanks in advance.

How to&Answers:

try adding IMEX=1;

HDR=Yes;IMEX=1″

Answer:

if you have a lot of rows,the type is the most type,else the type depend on the first line,the one answer’s type is string.