尝试更改Shape.Fill.Backcolor时,C#Excel Interop InvalidCastException

时间:2016-03-02 21:53:32

标签: c# excel exception interop

当我尝试在Excel工作表上更改通过C#创建的新形状的背景颜色时出现错误。我在下面添加了产生错误的示例代码。下面的代码在安装了Office 2013的旧PC上工作正常,但是当在客户端计算机或我的新PC上运行时(Windows 10 Office 2016),我在Shape.getFill()调用中获得了InvalidCastException(下面粘贴的异常)几乎没有其他电话。

抛出的所有调用似乎与获取格式化对象有关(例如,它也发生在Chart.PlotArea.Format.get_Line()调用上。我制作的大多数其他C#Excel Interop调用都正常工作。例如,我可以创建形状和图表,从单元格写入和读取,但当我尝试更改某些对象的格式时,会发生此错误。当我在新笔记本电脑上编译并运行以下代码时,我在旧笔记本电脑上编译并运行时会得到模糊的InvalidCastException工作没有错误。在旧机器上编译和运行并没有解决这个问题。我已经尝试在新PC上安装2010 PIA也没有运气。任何帮助将不胜感激。

代码示例

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Excel = Microsoft.Office.Interop.Excel;
using System.Runtime.InteropServices;

namespace TestOfficeError {
    static class Program {
        [STAThread]
        static void Main() {
            Excel.Application app = new Excel.Application();
            Excel.Workbooks wbs = app.Workbooks;
            Excel.Workbook wb = wbs.Add();
            Excel.Sheets sheets = wb.Sheets;
            Excel.Worksheet sheet = sheets[1];

            Excel.Shape shape = sheet.Shapes.AddShape(Microsoft.Office.Core.MsoAutoShapeType.msoShapeRectangle, 10, 10, 100, 100);

            //Exception thrown on this line. See exception below.
            shape.Fill.BackColor.RGB = 0;

            wb.Activate();

            SafeRelease(sheet);
            SafeRelease(sheets);
            SafeRelease(wb);
            SafeRelease(wbs);
            SafeRelease(app);
            FinalCleanup();

        }

        static void SafeRelease(object obj) {
            if (obj != null){
                Marshal.FinalReleaseComObject(obj);
            }
        }

        static void FinalCleanup() {
            GC.Collect();
            GC.WaitForPendingFinalizers();
            GC.Collect();
            GC.WaitForPendingFinalizers();
        }
    }
}

异常

System.InvalidCastException was unhandled
  HResult=-2147467262
  Message=Return argument has an invalid type.
  Source=mscorlib
  StackTrace:
       at System.Runtime.Remoting.Proxies.RealProxy.ValidateReturnArg(Object arg, Type paramType)
       at System.Runtime.Remoting.Proxies.RealProxy.PropagateOutParameters(IMessage msg, Object[] outArgs, Object returnValue)
       at System.RuntimeType.ForwardCallToInvokeMember(String memberName, BindingFlags flags, Object target, Int32[] aWrapperTypes, MessageData& msgData)
       at Microsoft.Office.Interop.Excel.Shape.get_Fill()
       at TestOfficeError.Program.Main() in c:\users\chris\documents\visual studio 2015\Projects\TestOfficeError\TestOfficeError\Program.cs:line 28
       at System.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: 

2 个答案:

答案 0 :(得分:0)

我刚刚遇到与Excel.Shape.Line属性类似的问题。问题是用户安装了64位版本的Office 2010。将其更改为32位版本解决了这个问题。

答案 1 :(得分:0)

我使用dynamic类型代替Excel.Shape来解决此问题。

这只是一种解决方法,但它正在发挥作用。