Excel Interop - 添加工作表并通过 return 值更改名称

Excel Interop - Add Worksheet and change name via return value

我正在尝试更改通过 Add 方法创建的工作表的名称,并使用它的 return 值。这是由 Whosebug 上的几个 answers 建议的。但它不起作用并给出错误代码 0x800401A8 的 COMException。其他两种方法工作正常。谁能告诉我为什么第一种方法不起作用?

代码:

Application excel = new Application();
Workbook wb = excel.Workbooks.Open(fileInfo.FullName);

// Creates a new worksheet, chart, or macro sheet. The new worksheet becomes the active sheet.
var sheet = wb.Sheets.Add(Before: Type.Missing, After: wb.Sheets[wb.Sheets.Count], Count: 1, Type: XlSheetType.xlWorksheet);

try
{
    ((Worksheet)sheet).Name = "ASDF";
    
    
} catch(COMException e)
{
    Trace.WriteLine($"Fail 1 - 0x{e.ErrorCode:X}");
}
try
{
    ((Worksheet)wb.ActiveSheet).Name = "ASDF";
} catch(COMException e)
{
    Trace.WriteLine($"Fail 2 - 0x{e.ErrorCode:X}");
}

try
{
    ((Worksheet) wb.Sheets[wb.Sheets.Count]).Name = "ASDF";
} catch (COMException e)
{
    Trace.WriteLine($"Fail 3 - 0x{e.ErrorCode:X}");
}

跟踪输出:

Fail 1 - 0x800401A8

异常详情:

threw an exception of type 'System.Runtime.InteropServices.COMException'
    Data: {System.Collections.ListDictionaryInternal}
    ErrorCode: -2147221080
    HResult: -2147221080
    HelpLink: null
    InnerException: null
    Message: "0x800401A8"
    Source: "Testfall-Manager"
    StackTrace: "   at Microsoft.Office.Interop.Excel._Worksheet.set_Name(String RHS)"
    TargetSite: {Void set_Name(System.String)}

它是 excel 文件本身。以上方法适用于空 excel 文件 (xlsx)