尝试在c#中更改工作表名称时出现奇怪的错误

时间:2015-03-24 18:06:26

标签: c# excel com

以下是抛出错误的代码:

string[] sheetNames = new string[] {"Raw"};

for (int s = 1; s <= sheetNames.Count(); s++)
{
    Excel.Worksheet newSheet = new Excel.Worksheet();
    newSheet.Name = sheetNames[s];
    newWorkbook.Worksheets.Add(newSheet);
}

我收到了Unable to cast COM object of type 'WorksheetClass' to interface type '_Worksheeet'个例外。我不知道这意味着什么。

感谢所有帮助

1 个答案:

答案 0 :(得分:2)

创建Worksheet对象的方法就是问题所在。您需要首先定义Application对象,然后调用类似:Application.WorkSheets.Add()的内容 例如:

Excel.Application xlApp = new Excel.Application();
xlApp.Visible = true;
Excel.Workbook xlWb = xlApp.Workbooks.Add() as Excel.Workbook;
Excel.Worksheet xlSheet = xlWb.Sheets[1] as Excel.Worksheet;