2010年9月10日 星期五

OleDb方式讀取 txt、dbf、xls

[txt]

string constr=@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source="+vsFilePath+";Extended Properties='text;HDR=Yes;FMT=Delimited;IMEX=1;'";
OleDbDataAdapter da=new OleDbDataAdapter ();
OleDbConnection OConn=new OleDbConnection ();
OConn.ConnectionString =constr;
OConn.Open ();
OleDbCommand OCmm=new OleDbCommand ();
OCmm.CommandText ="select * from "+filename+"#txt";
OCmm.Connection=OConn;
da.SelectCommand =OCmm;
OCmm.CommandTimeout=0;

try
{
da.Fill(ds,filename);
}
catch(Exception ex)
{
throw new Exception("Error!"+ex.Message.ToString());
}
finally
{
OConn.Close();
}

[dbf]

string constr="Driver={Microsoft Visual FoxPro Driver};SourceType=DBF;SourceDB="+vsFilePath;
OdbcDataAdapter da=new OdbcDataAdapter ();
OdbcConnection OConn=new OdbcConnection ();
OConn.ConnectionString =constr;
OConn.Open ();
OdbcCommand OCmm=new OdbcCommand ();
OCmm.CommandText ="Select "+fCol+" from "+filename;
OCmm.Connection=OConn;
da.SelectCommand =OCmm;
OCmm.CommandTimeout=0;
try
{
da.Fill(ds,filename);
}
catch(Exception ex)
{
throw new Exception("Error!"+ex.Message.ToString());
}
finally
{
OConn.Close();
}

[xls]

string constr=@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source="+vsFilePath+newnm+";Extended Properties='Excel 8.0;HDR=Yes;IMEX=1'";
OleDbDataAdapter da=new OleDbDataAdapter ();
OleDbConnection OConn=new OleDbConnection ();
OConn.ConnectionString =constr;
OConn.Open ();
OleDbCommand OCmm=new OleDbCommand ();
OCmm.CommandText ="select * from [sheet1$]";
OCmm.Connection=OConn;
da.SelectCommand =OCmm;
OCmm.CommandTimeout=0;
try
{
da.Fill(ds,filename);
}
catch(Exception ex)
{
throw new Exception("Error!"+ex.Message.ToString());
}
finally
{
OConn.Close();
}

沒有留言:

張貼留言