Thursday, February 17, 2011

How to read text/numeric data from Excel in .net

To read mixed mode like numeric and alphanumeric in same column means, oledb connection string should be as below, otherwise jet engine automatically take eighter numeric or text( data type value fill with NULL value).

Connection string: "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\MyExcel.xls;Extended Properties=""Excel 8.0;HDR=Yes;IMEX=1"""

here,
HDR=Yes;" indicates that the first row contains columnnames, not data. "HDR=No;" indicates the opposite.

"IMEX=1;" tells the driver to always read "intermixed" data columns as text. Note that this option might affect excel sheet write access negative.

Sample Source:
bool GetExcelData(string ExcelFileNameWithPath, out DataSet ds, ref string ErrorMessage)
{
bool bResult = false;
string strQuery = String.Empty;
string strConnectionString = String.Empty;
System.Data.OleDb.OleDbCommand cmd = null;
System.Data.OleDb.OleDbConnection con = null;
System.Data.OleDb.OleDbDataAdapter da = null;

strQuery = "SELECT * FROM [Sheet1$] ";

ds = new DataSet();
try
{

strConnectionString = String.Format(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties=""Excel 8.0;HDR=Yes;IMEX=1"";", ExcelFileNameWithPath);

if (!System.IO.File.Exists(ExcelFileNameWithPath))
throw new System.Exception("File not found, source file does not exit!");


using (con = new OleDbConnection(strConnectionString))
{
con.Open();
cmd = new OleDbCommand();

cmd.Connection = con;
cmd.CommandType = CommandType.Text;
cmd.CommandText = strQuery;

da = new OleDbDataAdapter(cmd);
da.Fill(ds, "RECORDS");

bResult = true;

}
}
catch (Exception exp)
{
//Log error Message
//String.Format("Error occured during data retrive from source, Msg={0}, Trace={1}", exp.Message, exp.StackTrace);
}
finally
{
if ( con != null && con.State ==ConnectionState.Open)
con.Close();
}


return bResult;
}

Source Ref : http://social.msdn.microsoft.com/forums/en-US/adodotnetdataproviders/thread/0d754ec0-e642-44de-9aa2-1e3487db0a2c/

No comments: