为什么在将工作表分配给工作表变量时出现类型不匹配?

Why am I getting a Type Mismatch when assigning a Worksheet to a Worksheet var?

我正在尝试将 Aspose Cells for .NET 合并到这个使用 Excel Interop 的 class 中(而不是重写整个东西以使用 Aspose Cells,我现在正在尝试,我想至少从混合方法开始。

问题是我得到一个 "Type mismatch" 异常代码:

private Workbook _xlBook;
. . .
Worksheet asposePT = _xlBook.Worksheets[_xlBook.Worksheets.Add()];

我的项目引用了 Aspose.Cells,版本 16.11.0.0(运行时版本 v4.0.30319)

我在 class 文件中有这些用法:

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Threading;
using System.Windows.Forms;
using ReportRunner.SharedCode;
using Microsoft.Office.Interop.Excel;
using System.Runtime.InteropServices;
using System.Text;
using Excel = Microsoft.Office.Interop.Excel;

这是异常详细信息:

System.Runtime.InteropServices.COMException was caught
  HResult=-2147352571
  Message=Type mismatch. (Exception from HRESULT: 0x80020005 (DISP_E_TYPEMISMATCH))
  Source=System.Dynamic
  ErrorCode=-2147352571
  StackTrace:
       at System.Dynamic.ComRuntimeHelpers.CheckThrowException(Int32 hresult, ExcepInfo& excepInfo, UInt32 argErr, String 
message)
       at CallSite.Target(Closure , CallSite , ComObject , Object )
       at System.Dynamic.UpdateDelegates.UpdateAndExecute2[T0,T1,TRet](CallSite site, T0 arg0, T1 arg1)
       at CallSite.Target(Closure , CallSite , Sheets , Object )
       at System.Dynamic.UpdateDelegates.UpdateAndExecute2[T0,T1,TRet](CallSite site, T0 arg0, T1 arg1)
       at ReportRunner.ProduceUsage.ProduceUsageRpt.PopulatePivotTableSheetAsposeCells() in c:\Projects\ReportRunner - 
Private Build\ReportRunner\ProduceUsage\ProduceUsageRpt.cs:line 1550
       at ReportRunner.ProduceUsage.ProduceUsageRpt.GenerateProduceUsageRpt() in c:\Projects\ReportRunner - Private Build
\ReportRunner\ProduceUsage\ProduceUsageRpt.cs:line 167
  InnerException: 
ProduceUsageRpt.cs:line 1550 is:
Worksheet asposePT = _xlBook.Worksheets[_xlBook.Worksheets.Add()];

我需要 "using Aspose" 或类似的东西吗?我是否需要将 Worksheet 显式声明为 Aspose Worksheet(与 Excel Interop 相反),或者什么?

更新

即使我更改了代码:

Worksheet asposePT = _xlBook.Worksheets[_xlBook.Worksheets.Add()];
asposePT.Name = "AsposePivotTable";
Aspose.Cells.Pivot.PivotTableCollection pivotTables = asposePT.PivotTables();

...对此(最后一行末尾的括号未被删除):

Aspose.Cells.Worksheet asposePT = _xlBook.Worksheets[_xlBook.Worksheets.Add()];
asposePT.Name = "AsposePivotTable";
Aspose.Cells.Pivot.PivotTableCollection pivotTables = asposePT.PivotTables;

...我仍然遇到同样的异常。

嗯,Aspose.Cells APIs(一个独立的 .NET 库)和 MS Excel Interop(办公自动化)APIs 在很多方面都不同,两者具有不同的体系结构,因此您不能仅根据 API b/w 来解析对象。我认为你应该只使用 Aspose.Cells APIs 来实例化工作簿(电子表格),add/update 或将数据操作到工作表等,最后保存 Excel 文件。我猜你的基础 _xlBook 对象可能是你可能已经针对 MS Excel Interop 实例化的罪魁祸首。 APIs.

我在 Aspose 担任支持开发人员/传播者。