0

我正在运行此代码以获取 Cell 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;
        }
    }
}
4

3 回答 3

2

尝试先打开连接

excelConnection.Open()

于 2013-07-31T19:58:12.973 回答
1

您创建OleDbConnection对象,但从不调用Open实际建立连接。

于 2013-07-31T19:56:13.140 回答
0

你写道:

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

如果文本中没有智能/引用部分,那么字符串中的 + 符号有什么用?这不等于:

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

还是我在那里遗漏了什么?

于 2013-10-10T11:17:36.933 回答