无法将类型 'object' 隐式转换为'Microsoft.Office.Interop.Excel.Worksheet'



我有以下类。我从另一个程序转到创建一个ClassLibary。

我在我有 wb 的任何地方收到下面的错误消息。沃克希特

不能将类型"对象"隐式转换为"Microsoft.Office.Interop.Excel.Worksheet"。存在显式转换(您是否缺少强制转换?

该类在原始程序中工作。 我添加了引用 Inereop.Microsoft.Office.Interop.Excel

using System;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Office.Interop.Excel;
using _Excel = Microsoft.Office.Interop.Excel;
public class Excel
{
string path = "";
_Application excel = new _Excel.Application();
Workbook wb;
Worksheet ws;
public Excel()
{
}
public Excel(string path, int sheet)
{
this.path = path;
wb = excel.Workbooks.Open(path);
ws = wb.Worksheets[sheet];
}
public void Open(string path, int sheet)
{
this.path = path;
wb = excel.Workbooks.Open(path);
ws = wb.Worksheets[sheet];
}
public void CreateNewFile()
{
this.wb = excel.Workbooks.Add(XlWBATemplate.xlWBATWorksheet);
this.ws = wb.Worksheets[1];
}
}
}

使用以下样式添加显式类型转换:

ws = (Microsoft.Office.Interop.Excel.Worksheet)wb.Worksheets[sheet];

使用显式转换时,您必须确定目标类型。在文档中指出,工作表集合可以同时包含图表和工作表对象。

csproj更新Reference Include="Microsoft.Office.Interop.Excel"以嵌入互操作类型。这将允许使用dynamic而不是普通object类型。

<Reference Include="Microsoft.Office.Interop.Excel">
<HintPath>C:Program Files (x86)Microsoft Visual StudioSharedVisual Studio Tools for OfficePIAOffice14Microsoft.Office.Interop.Excel.dll</HintPath>
<EmbedInteropTypes>True</EmbedInteropTypes>
</Reference>

相关内容

最新更新