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

Weird error when trying to change worksheet name in c#

这是抛出错误的代码:

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' 异常。我不知道那是什么意思。

感谢所有帮助

您创建 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;