我有以下课程。我从另一个程序移到一个ClassLibary。
我在有wb.Worksheeet的任何地方都收到错误消息
无法将类型“对象”隐式转换为“ 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];
}
}
}
答案 0 :(得分:3)
添加具有以下样式的显式类型转换:
ws = (Microsoft.Office.Interop.Excel.Worksheet)wb.Worksheets[sheet];
通过显式转换,您必须确定目标类型。 In documentation指出,工作表集合可以同时包含图表和工作表对象。