Click here to Skip to main content
15,885,919 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,
I want to cast value while reading it from excel use oldDB. my code is below.
DataTable dtOleDB = new DataTable();
        string constr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + xlsFileName + ";    Extended Properties='Excel 12.0 Xml;HDR=YES;'";
        OleDbConnection oledbCon = new OleDbConnection(constr);
        string cmdText = "SELECT Cast(ExceptionID as varchar), [FeatureOptionID], ExceptionTypeID, ExceptionFeatureOptionID, ";
        cmdText += "AlternateDescription FROM [Exceptions$]";
        OleDbDataAdapter oleDA = new OleDbDataAdapter(cmdText, oledbCon);
        oleDA.Fill(dtOleDB);


If using without cast its working fine. But I want to cast it in varchar format like do in sql server how can I achieve this functionality here.

thanks
Posted
Updated 12-Jan-21 20:34pm
Comments
Sampath Lokuge 23-Jan-14 8:08am    
why do you need that ?
ShivKrSingh 23-Jan-14 23:02pm    
I'm using excel file in my application and want to check if someone enter text in ID field it should be validate. but when we read it text is not displaying if it is not in number format. While value exist in excel file. if I format that column as text in excel sheet it goes well. But this file generate at runtime and destroy. so I want a solution that can help me conversion. without any manual change in excel file.

Try this, it might help you.
cast-a-data-type-with-the-odbc-excel-driver[^]
 
Share this answer
 
The Microsoft.ACE.OLEDB provider being the "Microsoft Access Database Engine" uses MS Access SQL syntax.

You will need to use the type conversion functions available in Access[^].

You should also be checking for null values before attempting the conversion.

Cast(ExceptionID as varchar) would be:

IIf(IsNull([ExceptionID]), Null, CStr([ExceptionID])) As strExceptionID

In this example, a DBNull will be returned if the Excel cell is empty. If you want to return an empty String then it would be:
IIf(IsNull([ExceptionID]), '', CStr([ExceptionID])) As strExceptionID
 
Share this answer
 
You cannot use CAST with OLEDb provider.
 
Share this answer
 
Comments
ShivKrSingh 23-Jan-14 23:03pm    
what is the alternative of this while using with excel.
Abhinav S 23-Jan-14 23:21pm    
Fetch the data and then convert using C# code.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900