为什么我会得到," InteropServices.COMException / ForwardCallToInvokeMember"使用此代码?

时间:2016-06-20 23:09:11

标签: c# excel-interop comexception interopservices invokemember

检索数据并将其存储在通用列表中后,我已使用Excel Interop代码填写Excel电子表格中的代码:

. . .
InitializeExcelObjects();
_currentTopRow = DATA_STARTING_ROW;
foreach (PriceVarianceData _pvd in _pvdList)
{
    AddData(_pvd);
    _currentTopRow = _currentTopRow + 1;
}
. . .

private void AddData(PriceVarianceData _pvd)
{
    var UnitCell = (Excel.Range)_xlSheet.Cells[_currentTopRow, 0];
    UnitCell.Value2 = _pvd.Unit;
    var ShortNameCell = (Excel.Range)_xlSheet.Cells[_currentTopRow, 1];
    ShortNameCell.Value2 = _pvd.ShortName;
    . . .
}

它在AddData()方法的第一行崩溃(尝试分配给UnitCell)," System.Runtime.InteropServices.COMException未处理... StackTrace:在System.RuntimeType。 ForwardCallToInvokeMember(String memberName,BindingFlags flags,Object ... "

我不知道为什么会这样;我在尝试添加数据之前先调用它:

private void InitializeExcelObjects()
{
    _xlApp = new Excel.Application
    {
        SheetsInNewWorkbook = 1,
        StandardFont = "Calibri",
        StandardFontSize = 11
    };
    Thread.Sleep(2000);
    //var apartmentSt8 = Thread.CurrentThread.GetApartmentState(); <= STA, as it should be

    _xlBook = _xlApp.Workbooks.Add(Type.Missing);
    _xlSheets = _xlBook.Worksheets;
    _xlSheet = (Excel.Worksheet)_xlSheets.Item[1];
}

完整的例外是:

System.Runtime.InteropServices.COMException未处理   的HResult = -2146827284   消息=来自HRESULT的异常:0x800A03EC   源=&#34;&#34;   错误码= -2146827284   堆栈跟踪:        at System.RuntimeType.ForwardCallToInvokeMember(String memberName,BindingFlags flags,Object target,Int32 [] aWrapperTypes,MessageData&amp; msgData)        在Microsoft.Office.Interop.Excel.Range.get__Default(Object RowIndex,Object ColumnIndex)        在C:\ Projects \ Pivotal \ Pivotal \ Form1.cs中的Pivotal.FormMain.AddData(PriceVarianceData _pvd):第155行        在C:\ Projects \ Pivotal \ Pivotal \ Form1.cs中的Pivotal.FormMain.GenerateAndSaveSpreadsheetFile():第134行        在Pivotal.FormMain.buttonRun_Click(Object sender,EventArgs e)中的c:\ Projects \ Pivotal \ Pivotal \ Form1.cs:第77行        在System.Windows.Forms.Control.OnClick(EventArgs e)        在System.Windows.Forms.Button.OnClick(EventArgs e)        在System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent)        在System.Windows.Forms.Control.WmMouseUp(消息&amp; m,MouseButtons按钮,Int32点击)        在System.Windows.Forms.Control.WndProc(消息&amp; m)        在System.Windows.Forms.ButtonBase.WndProc(消息&amp; m)        在System.Windows.Forms.Button.WndProc(消息&amp; m)        在System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message&amp; m)        在System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message&amp; m)        在System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd,Int32 msg,IntPtr wparam,IntPtr lparam)        在System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG&amp; msg)        在System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(IntPtr dwComponentID,Int32 reason,Int32 pvLoopData)        在System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason,ApplicationContext context)        在System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason,ApplicationContext context)        在System.Windows.Forms.Application.Run(Form mainForm)        在Pivotal.Program.Main()在c:\ Projects \ Pivotal \ Pivotal \ Program.cs:第19行        在System.AppDomain._nExecuteAssembly(RuntimeAssembly程序集,String [] args)        在System.AppDomain.ExecuteAssembly(String assemblyFile,Evidence assemblySecurity,String [] args)        在Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()        在System.Threading.ThreadHelper.ThreadStart_Context(对象状态)        at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext,ContextCallback callback,Object state,Boolean preserveSyncCtx)        at System.Threading.ExecutionContext.Run(ExecutionContext executionContext,ContextCallback callback,Object state,Boolean preserveSyncCtx)        在System.Threading.ExecutionContext.Run(ExecutionContext executionContext,ContextCallback回调,对象状态)        在System.Threading.ThreadHelper.ThreadStart()   InnerException:

这可能是什么问题?我看了this,但没有一个建议似乎适用于这种情况。

更新

我今天早上注意到我有大约40个Excel进程正在运行,所以想知道这可能是问题(他们不会被关闭/丢弃,我猜)并将它们全部杀掉。尽管如此,我仍然有相同的结果 - 而且Excel流程也很常见(正如可以预料的那样,突然停止执行)。

1 个答案:

答案 0 :(得分:3)

AddData()方法的第一行中,您尝试使用基于0的索引访问Cells,但excel中的列和行索引都是基于1的索引(事实上,Excel中的许多索引都是基于1的 - 但不是全部。

要解决这个问题,你必须做两件事:

  1. 确保_currentTopRow是基于1的索引(即最小有效值为1)
  2. 按如下方式更改AddData()方法:

    private void AddData(PriceVarianceData _pvd)
    {
        // Note changed column index (from 0 to 1)
        var UnitCell = (Excel.Range)_xlSheet.Cells[_currentTopRow, 1];
        UnitCell.Value2 = _pvd.Unit;
    
        // Note changed column index (from 1 to 2)
        var ShortNameCell = (Excel.Range)_xlSheet.Cells[_currentTopRow, 2];
    
        ShortNameCell.Value2 = _pvd.ShortName;
        . . .
    }