C#读取Excel文件:通过OleDb连接,把excel文件作为数据源来读取

时间:2014-01-17 00:15:53   收藏:0   阅读:586

转载于:http://developer.51cto.com/art/200908/142392.htm


C#读取Excel文件可以通过直接读取和OleDb连接,把excel文件作为数据源来读取;

 


 

 

C#读取Excel文件方法二:通过OleDb连接,把excel文件作为数据源来读取(这里是fill进dataset,也可以返回OleDbDataReader来逐行读,数据较快)

注:这种方法容易把混合型的字段作为null值读取进来,解决办法是改造连接字符串

strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\\Erp1912.xls;Extended Properties=‘Excel8.0;HDR=Yes;IMEX=1‘";

通过Imex=1来把混合型作为文本型读取,避免null值,来实现C#读取Excel文件

 
private DataSet importExcelToDataSet(string FilePath) 
   string strConn; 
   strConn="Provider=Microsoft.Jet.OLEDB.4.0;"+"DataSource="+FilePath+";Extended Properties=Excel8.0;"
   OlebConnection conn=new OleDbConnection(strConn); 
   OleDbDataAdapter myCommand=new OleDbDataAdapter("SELECT*FROM[Sheet1$]",strConn); 
   DataSetmyDataSet=newDataSet(); 
   try 
   
     myCommand.Fill(myDataSet); 
   
   catch(Exceptionex) 
   
      throw new InvalidFormatException("该Excel文件的工作表的名字不正确,"+ex.Message); 
   
   returnmyDataSet; 
}

原文:http://www.cnblogs.com/-------perfect/p/3522247.html

评论(0
© 2014 bubuko.com 版权所有 - 联系我们:wmxa8@hotmail.com
打开技术之扣,分享程序人生!