为什么我会得到 "InteropServices.COMException / ForwardCallToInvokeMember" 这个代码?

Why would I get, "InteropServices.COMException / ForwardCallToInvokeMember" with this code?

检索数据并将其存储在通用列表中后,我得到了使用 Excel 互操作代码填充 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 来源=“” 错误代码=-2146827284 堆栈跟踪: 在 System.RuntimeType.ForwardCallToInvokeMember(String memberName, BindingFlags flags, Object target, Int32[] aWrapperTypes, MessageData& msgData) 在 Microsoft.Office.Interop.Excel.Range.get__Default(对象 RowIndex,对象 ColumnIndex) 在 Pivotal.FormMain.AddData(PriceVarianceData _pvd) 在 c:\Projects\Pivotal\Pivotal\Form1.cs:line 155 在 Pivotal.FormMain.GenerateAndSaveSpreadsheetFile() 在 c:\Projects\Pivotal\Pivotal\Form1.cs:134 行 在 Pivotal.FormMain.buttonRun_Click(Object sender, EventArgs e) in c:\Projects\Pivotal\Pivotal\Form1.cs:line 77 在 System.Windows.Forms.Control.OnClick(EventArgs e) 在 System.Windows.Forms.Button.OnClick(EventArgs e) 在 System.Windows.Forms.Button.OnMouseUp(MouseEventArgs 事件) 在 System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks) 在 System.Windows.Forms.Control.WndProc(留言& m) 在 System.Windows.Forms.ButtonBase.WndProc(消息& m) 在 System.Windows.Forms.Button.WndProc(消息& m) 在 System.Windows.Forms.Control.ControlNativeWindow.OnMessage(消息& m) 在 System.Windows.Forms.Control.ControlNativeWindow.WndProc(消息& m) 在 System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam) 在 System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(味精&味精) 在 System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(IntPtr dwComponentID,Int32 原因,Int32 pvLoopData) 在 System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 原因,ApplicationContext 上下文) 在 System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 原因,ApplicationContext 上下文) 在 System.Windows.Forms.Application.Run(窗体主窗体) 在 Pivotal.Program.Main() 在 c:\Projects\Pivotal\Pivotal\Program.cs:line 19 在 System.AppDomain._nExecuteAssembly(RuntimeAssembly 程序集,字符串 [] 参数) 在 System.AppDomain.ExecuteAssembly(字符串 assemblyFile,证据 assemblySecurity,字符串 [] args) 在 Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly() 在 System.Threading.ThreadHelper.ThreadStart_Context(对象状态) 在 System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext、ContextCallback 回调、对象状态、布尔值 preserveSyncCtx) 在 System.Threading.ExecutionContext.Run(ExecutionContext executionContext、ContextCallback 回调、对象状态、布尔值 preserveSyncCtx) 在 System.Threading.ExecutionContext.Run(ExecutionContext executionContext,ContextCallback 回调,对象状态) 在 System.Threading.ThreadHelper.ThreadStart() 内部异常:

这可能是什么问题?我查看了 this,但 none 的建议似乎适用于这种情况。

更新

我今天早上注意到我有大约 40 个 Excel 进程 运行,所以想知道这是否可能是问题所在(他们没有关闭 down/disposed,我猜)把他们都杀了。不过,我仍然得到了相同的结果 - Excel 进程也一直存在(正如所料,突然停止执行)。

在您的 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;
        . . .
    }