2017-06-12 95 views
0

我想從Excel文件中讀取數據。該文件的路徑在配置文件中設置。我創建了一個用於連接目的的庫類,另一個庫類用於存儲在c#對象中檢索的值。我完全在控制檯應用程序上運行它。但是我最終在Conn.Open()中獲得了無效的參數異常。Conn.Open()中的OleDbConnection錯誤

類型 'System.Data.OleDb.OleDbException' 出現在system.data.dll附加信息的未處理的異常:無效的參數

這是我的Connection類

using System; 
using System.Collections.Generic; 
using System.Configuration; 
using System.Data; 
using System.Data.OleDb; 
using System.Linq; 
using System.Text; 
using System.Threading.Tasks; 

namespace ExcelLib 
{ 
    public class ExcelLib 
    { 
    public DataSet Excel() 
    { 
     string filepath = 
     Convert.ToString(ConfigurationManager.AppSettings["Path"]); 
     string conStr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filepath 
     + ";Extended Properties=\"Excel 12.0;ReadOnly=True;HDR=Yes;\""; 
     string query = "Select * from [jobs_productioncontrol$]"; 
     using (OleDbConnection conn = new OleDbConnection(conStr)) 
     { 
     conn.Open(); 
     OleDbCommand cmd = new OleDbCommand(query, conn); 
     cmd.Connection = conn; 

     OleDbDataAdapter command = new OleDbDataAdapter(); 
     command.SelectCommand = cmd; 
     DataSet ds = new DataSet(); 
     command.Fill(ds); 

     DataTable dt = new DataTable(); 
     dt = ds.Tables.Add(); 

     foreach (DataRow row in dt.Rows) 
     { 
      ExcelData data = new ExcelData(); 
      data.JobNo = row["JobNo"].ToString(); 
      data.EventNo = row["EventNo"].ToString(); 
     } 
     return ds; 
     } 
    } 
    } 
} 
+2

你有什麼異常?什麼是異常信息? –

+0

System.Data.dll中發生未處理的「System.Data.OleDb.OleDbException」類型異常 附加信息:無效參數。 – kulbans1991

+0

你可以在調試模式下運行你的項目並查看'filepath'的值嗎? –

回答

0

根據對問題的評論,filepathnull,表示appSettings已按預期配置。 App.config文件需要與消費應用程序關聯,而不是類庫。

我強烈建議消費應用程序負責加載可配置的設置並將它們傳播到類庫中。這可能會阻止這個問題,並且可能會防止將來出現其他混淆源。