我有以下类(class)。我从另一个程序转移来创建一个 ClassLibary。
我在拥有 wb.Worksheet 的任何地方都收到下面的错误消息
无法将类型“object”隐式转换为“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];
通过显式转换,您必须确定目标类型。 In documentation据说 Worksheets-collection 可以包含 Charts 和 Worksheet 对象。
关于c# - 无法将类型 'object' 隐式转换为 'Microsoft.Office.Interop.Excel.Worksheet',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55695702/