2013-07-31 49 views
0

我正在運行此代碼以獲取單元格A3的值,但它給了我錯誤。C#代碼失敗 - 試圖獲得excel單元格A3值

我正在使用SSIS來獲得excel單元格A3,現在我想在消息框中顯示它,但後來我將存儲在變量中。

Error: System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.InvalidOperationException: ExecuteReader requires an open and available Connection. The connection's current state is closed. 
    at System.Data.OleDb.OleDbConnection.CheckStateOpen(String method) 
    at System.Data.OleDb.OleDbCommand.ValidateConnection(String method) 
    at System.Data.OleDb.OleDbCommand.ValidateConnectionAndTransaction(String method) 
    at System.Data.OleDb.OleDbCommand.ExecuteReaderInternal(CommandBehavior behavior, String method) 
    at System.Data.OleDb.OleDbCommand.ExecuteReader(CommandBehavior behavior) 
    at System.Data.OleDb.OleDbCommand.ExecuteReader() 
    at ST_863f36c5697844e3916f1142373f3d3a.csproj.ScriptMain.Main() 
    --- End of inner exception stack trace --- 
    at System.RuntimeMethodHandle._InvokeMethodFast(Object target, Object[] arguments, SignatureStruct& sig, MethodAttributes methodAttributes, RuntimeTypeHandle typeOwner) 
    at System.RuntimeMethodHandle.InvokeMethodFast(Object target, Object[] arguments, Signature sig, MethodAttributes methodAttributes, RuntimeTypeHandle typeOwner) 
    at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture, Boolean skipVisibilityChecks) 
    at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture) 
    at System.RuntimeType.InvokeMember(String name, BindingFlags bindingFlags, Binder binder, Object target, Object[] providedArgs, ParameterModifier[] modifiers, CultureInfo culture, String[] namedParams) 
    at System.Type.InvokeMember(String name, BindingFlags invokeAttr, Binder binder, Object target, Object[] args, CultureInfo culture) 
    at Microsoft.SqlServer.Dts.Tasks.ScriptTask.VSTATaskScriptingEngine.ExecuteScript() 

這裏是代碼

/* 
    Microsoft SQL Server Integration Services Script Task 
    Write scripts using Microsoft Visual C# 2008. 
    The ScriptMain is the entry point class of the script. 
*/ 

using System; 
using System.Data; 
using Microsoft.SqlServer.Dts.Runtime; 
using System.Windows.Forms; 
using System.Data.OleDb; 

namespace ST_863f36c5697844e3916f1142373f3d3a.csproj 
{ 
    [System.AddIn.AddIn("ScriptMain", Version = "1.0", Publisher = "", Description = "")] 
    public partial class ScriptMain : Microsoft.SqlServer.Dts.Tasks.ScriptTask.VSTARTScriptObjectModelBase 
    { 

     #region VSTA generated code 
     enum ScriptResults 
     { 
      Success = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Success, 
      Failure = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Failure 
     }; 
     #endregion 

     /* 
     The execution engine calls this method when the task executes. 
     To access the object model, use the Dts property. Connections, variables, events, 
     and logging features are available as members of the Dts property as shown in the following examples. 

     To reference a variable, call Dts.Variables["MyCaseSensitiveVariableName"].Value; 
     To post a log entry, call Dts.Log("This is my log text", 999, null); 
     To fire an event, call Dts.Events.FireInformation(99, "test", "hit the help message", "", 0, true); 

     To use the connections collection use something like the following: 
     ConnectionManager cm = Dts.Connections.Add("OLEDB"); 
     cm.ConnectionString = "Data Source=localhost;Initial Catalog=AdventureWorks;Provider=SQLNCLI10;Integrated Security=SSPI;Auto Translate=False;"; 

     Before returning from this method, set the value of Dts.TaskResult to indicate success or failure. 

     To open Help, press F1. 
    */ 

     public void Main() 
     { 

      string connectionString = null; 
      OleDbConnection excelConnection = null; 

      connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + "C:\\NewFolder\\Test.xlsx" + ";Extended Properties=\"Excel 12.0;HDR=NO;IMEX=1\";"; 

      excelConnection = new OleDbConnection(connectionString); 
      // Currentable is the Sheetname 
      string strSQL = "Select * From [" + "Sheet1$" + "A3:A3]"; 
      int iCnt = 4; 
      OleDbCommand objcmd = new OleDbCommand(strSQL, excelConnection); 
      //int endpos = 1; 
      //int startpos = 0; 
      //Boolean startflag = true; 
      //Boolean flag = true; 
      OleDbDataReader objReader = objcmd.ExecuteReader(); 
      int nullcount = 0; 
      // MessageBox.Show(objReader.FieldCount.ToString()); 
      try 
      { 
       // MessageBox.Show("Before while"); 
       while (objReader.Read()) 
       { 
        // Checking for NULLS as there are blank rows in between actual Excel row data. GETVALUE(2) searches in the B column of Excel 
        if (objReader.GetValue(2) == DBNull.Value) 
        { 
         nullcount = nullcount + 1; 
         // MessageBox.Show("Null"); 
        } 
        if (objReader.GetValue(2) != DBNull.Value) 
        { 
         // MessageBox.Show(objReader.GetValue(2).ToString()); 
         iCnt = iCnt + 1; 
        } 



       } 
      } 
      catch (Exception e) 
      { 
       MessageBox.Show(e.StackTrace.ToString()); 
      } 




      Dts.TaskResult = (int)ScriptResults.Success; 
     } 
    } 
} 

回答

1

您創建OleDbConnection對象,但永遠不會調用Open實際建立連接。

2

嘗試打開連接第一

excelConnection.Open()

0

ü寫道:

string strSQL = "Select * From [" + "Sheet1$" + "A3:A3]"; 

如果在沒有文字 - 智能/引用的部分,那麼什麼用的+號那裏的字符串?是不是那euqal:

string strSQL = "Select * From [Sheet1$A3:A3]"; 

或者我錯過了那裏的東西?

+1

是的,你是對的,但錯誤的原因是連接沒有打開。 – Halvard

+0

right @Halvard我同意,但讓我們說我們添加行來打開連接,但strSQL字符串將獲取什麼? [Sheet1 $ A3:A3]是否正確? – gsvirdi

+0

是的,我相信。它返回一個'SheetRange',其中只有一個元素(從A3到A3)。 – Halvard