简体   繁体   English

为什么使用此代码会得到“ InteropServices.COMException / ForwardCallToInvokeMember”?

[英]Why would I get, “InteropServices.COMException / ForwardCallToInvokeMember” with this code?

After retrieving data and storing it in a generic list, I've got this code to populate an Excel spreadsheet using Excel Interop code: 检索数据并将其存储在通用列表中之后,我得到了以下代码,以使用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;
    . . .
}

It crashes on the first line of the AddData() method (the attempted assignment to UnitCell), with " System.Runtime.InteropServices.COMException was unhandled... StackTrace: at System.RuntimeType.ForwardCallToInvokeMember(String memberName, BindingFlags flags, Object... " 它在AddData()方法的第一行(尝试分配给UnitCell的文件)上崩溃, 未处理System.Runtime.InteropServices.COMException ... StackTrace:位于System.RuntimeType.ForwardCallToInvokeMember(String memberName,BindingFlags标志,Object ...

I don't know why this would be; 我不知道为什么会这样。 I'm calling this prior to trying to add data: 在尝试添加数据之前,我先打电话给我:

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];
}

The full exception is: 完整的例外是:

System.Runtime.InteropServices.COMException was unhandled HResult=-2146827284 Message=Exception from HRESULT: 0x800A03EC Source="" ErrorCode=-2146827284 StackTrace: at System.RuntimeType.ForwardCallToInvokeMember(String memberName, BindingFlags flags, Object target, Int32[] aWrapperTypes, MessageData& msgData) at Microsoft.Office.Interop.Excel.Range.get__Default(Object RowIndex, Object ColumnIndex) at Pivotal.FormMain.AddData(PriceVarianceData _pvd) in c:\\Projects\\Pivotal\\Pivotal\\Form1.cs:line 155 at Pivotal.FormMain.GenerateAndSaveSpreadsheetFile() in c:\\Projects\\Pivotal\\Pivotal\\Form1.cs:line 134 at Pivotal.FormMain.buttonRun_Click(Object sender, EventArgs e) in c:\\Projects\\Pivotal\\Pivotal\\Form1.cs:line 77 at System.Windows.Forms.Control.OnClick(EventArgs e) at System.Windows.Forms.Button.OnClick(EventArgs e) at System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent) at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks) at System.Windows.Forms.C 未处理System.Runtime.InteropServices.COMException HResult = -2146827284消息=来自HRESULT的异常:0x800A03EC Source =“” ErrorCode = -2146827284 StackTrace:位于System.RuntimeType.ForwardCallToInvokeMember(String memberName,BindingFlags标志,对象目标,Int32 [] aWrapperTypes ,Microsoft.Office.Interop.Excel.Range.get__Default(Object RowIndex,Object ColumnIndex)处的MessageData和msgData)在c:\\ Projects \\ Pivotal \\ Pivotal \\ Form1.cs:line 155处的C:\\ Projects.Pivotal \\ Pivotal \\ Form1.cs:line c:\\ Projects \\ Pivotal \\ Pivotal \\ Form1.cs中的Pivotal.FormMain.GenerateAndSaveSpreadsheetFile():c:\\ Projects \\ Pivotal \\ Pivotal \\ Form1.cs中Pivotal.FormMain.buttonRun_Click(Object sender,EventArgs e)的第134行: System.Windows.Forms.Button.OnClick(EventArgs e)在System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent)在System.Windows.Forms的第77行.System.Windows.Forms.C中的.Control.WmMouseUp(Message&m,MouseButtons button,Int32 clicks) ontrol.WndProc(Message& m) at System.Windows.Forms.ButtonBase.WndProc(Message& m) at System.Windows.Forms.Button.WndProc(Message& m) at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m) at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m) at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam) at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg) at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(IntPtr dwComponentID, Int32 reason, Int32 pvLoopData) at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context) at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context) at System.Windows.Forms.Application.Run(Form mainForm) at Pivotal.Program.Main() in c:\\Projects\\Pivotal\\Pivotal\\Program.cs:line 19 at S System.Windows.Forms.ButtonBase上的ontrol.WndProc(Message&m).System.Windows.Forms.Button.WndProc(Message&m)在System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message&m) )在System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd,Int32 msg,IntPtr wparam,IntPtr lparam)在System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW处的System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message&m) (MSG和msg),位于System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32原因,在System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32原因,ApplicationContext上下文)在System.Windows.Forms.Application.Run(Form mainForm)在Pivotal.Program.Main()在c:\\ Projects \\ Pivotal \\ Pivotal \\ Program.cs:S的第19行 ystem.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args) at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args) at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly() at System.Threading.ThreadHelper.ThreadStart_Context(Object state) 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) at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state) at System.Threading.ThreadHelper.ThreadStart() InnerException: ystem.AppDomain._nExecuteAssembly(RuntimeAssembly程序集,String [] args)在System.AppDomain.ExecuteAssembly(String assemblyFile,证据AssemblySecurity,String [] args)在Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()在System.Threading.ThreadHelper System.Threading.ExecutionContext.Run(ExecutionContext执行上下文,ContextCallback回调,对象状态,布尔型saveSyncCtx)在System.Threading.ExecutionContext.RunInternal(ExecutionContext执行上下文,ContextCallback回调,对象状态,布尔值saveSyncCtx) System.Threading.ThreadHelper.ThreadStart()上的.Threading.ExecutionContext.Run(ExecutionContext executeContext,ContextCallback回调,对象状态)InnerException:

What could be the issue here? 这里可能是什么问题? I looked at this , but none of the suggestions seemed to apply to this situation. 我看着这个 ,但没有建议似乎适用于这种情况。

UPDATE 更新

I noticed this morning that I had about 40 Excel processes running, so wondered if that might be the problem (they're not getting shut down/disposed, I guess) and killed them all. 我今天早上注意到我正在运行大约40个Excel进程,所以想知道这是否是问题所在(我想它们没有被关闭/处置)并杀死了所有这些进程。 I still had the same result, though - and that Excel process also hung around (as could be expected, what with the sudden cessation of execution). 但是,我仍然得到相同的结果-而且Excel流程也仍然存在(可以预期,突然停止执行该怎么办)。

In the first line of your AddData() method you are trying to access the Cells with a 0-based index, but the column- and row-indexes in excel are all 1-based indexes (in fact many indexes in Excel are 1-based - but not all). 在您的AddData()方法的第一行中,您尝试使用基于0的索引访问Cells ,但是excel中的列索引和行索引都是基于1的索引(实际上Excel中的许多索引都是1-基于-但并非全部)。

To fix this you'll have to do 2 things in your case: 要解决此问题,您必须根据自己的情况做两件事:

  1. Ensure that _currentTopRow is a 1-based index (ie minimum valid value is 1) 确保_currentTopRow是从1开始的索引(即最小有效值为1)
  2. Change your AddData() method as follows: 更改您的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; . . . } 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 间歇性的“ InteropServices.COMException / ForwardCallToInvokeMember”在范围单元格上访问Value2 - Intermittent “InteropServices.COMException / ForwardCallToInvokeMember” accessing Value2 on Range cell 为什么我在尝试从 C# 启动 QTP 时收到 InteropServices.COMException? - Why do I get an InteropServices.COMException when attempting to launch QTP from C#? InteropServices.COMException - InteropServices.COMException 如何在不安装Excel的情况下修复InteropServices.COMException? - How can I fix InteropServices.COMException without installing Excel? 将项目添加到 ObservableCollection 时出现 InteropServices.COMException - InteropServices.COMException when adding item to ObservableCollection C# AutoIt InteropServices.COMException 错误 - C# AutoIt InteropServices.COMException error com 异常 excel InteropServices.COMException - c# - com exception excel InteropServices.COMException - c# 从ASP MVC控制器运行Word时保持获取InteropServices.COMException - Keep Getting InteropServices.COMException when running Word from ASP MVC Controller InteropServices.COMException(0x800A1066):在Teamcity下命令失败 - InteropServices.COMException (0x800A1066): Command failed under Teamcity 从页面调用静态异步方法导致 InteropServices.COMException 错误 - Calling a static async method from a Page results in InteropServices.COMException error
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM