C#讀取excel文件的內容(使用DataSet)


C#讀取Excel文件的內容,通過OLEDB來連接,關鍵是連接的路徑,
如:string strConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filePath + ";Extended Properties=Excel 12.0;";
     連接的路徑涉及3方面:

     1. Provider:使用的是OLEDB連接,但是這個技術會不時更新,使用前查詢最新的版本;

     2. Data Source: 就是Excel文件的路徑;

     3. Extended Properties: 指定Excel的版本,同上,使用前查詢最新的版本(要與讀取的Excel文件保存一致);

讀取不同的Sheet,方式跟SQL類似:
  string strExcel = "select * from [sheet3$]";

 1 public DataSet ReadFile(string filePath)
 2         {
 3             string strConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filePath + ";Extended Properties=Excel 12.0;"; 
 4             OleDbConnection conn = new OleDbConnection(strConn);
 5             conn.Open();
 6             string strExcel = "select * from [sheet3$]";
 7             OleDbDataAdapter da = new OleDbDataAdapter(strExcel, strConn);
 8             DataSet ds = new DataSet();
 9             try
10             {
11                 da.Fill(ds);
12             }
13             catch (Exception ex)
14             {
15                 throw new Exception("讀取Excel失敗:" + ex.Message);
16             }
17             return ds;
18         }
View Code

異常處理:

 1.如果出現 External table is not in the expected format.

      

      大部分都是因為路徑中的OLEDB或者Extended Properties與當前的Excel文件版本不對應導致的,本人當時就是如下情況:

      舊的:string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filePath + ";Extended Properties='Excel 8.0;HDR=NO;IMEX=1';";

  修改后:string strConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filePath + ";Extended Properties=Excel 12.0;";

  2.如果出現 The 'XXXXXXXXX' provider is not registered on the local machine

      

      那是因為Platform target配置不當的問題,OLEDB貌似只支持x86, 所以你只需要到項目屬性 -> Bulid -> Platform target -> x86就可以了

       

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM