如何使用 Excel 互操作保存启用宏的工作簿 (xlsm)?

How to save a macro enabled workbook (xlsm) with Excel interop?

尝试保存扩展名为 xlsm 的 Excel 工作簿时出现以下错误:

This extension can not be used with the selected file type. Change the file extension in the File name text box or select a different file type by changing the Save as type.

我的代码:

public static void CreateExcelfile()
{
    Excel.Application oXL = new Excel.Application();
    Excel.Workbook oWB = oXL.Workbooks.Add(Missing.Value);
    oWB.SaveAs("C:\Users\konanki\Documents\Sample.xlsm", Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Excel.XlSaveAsAccessMode.xlNoChange, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value);
    oWB.Close(true, Missing.Value, Missing.Value);
}

问题是您没有在 SaveAs 调用中提供文件格式。在您的情况下,您需要为 xlsm 指定 XlFileFormat.xlOpenXMLWorkbookMacroEnabled。另请注意,所有可选参数都不需要使用 Missing.Value,因为它们具有默认值。这应该有效:

public static void CreateExcelfile()
{
    Excel.Application oXL = new Excel.Application();
    Excel.Workbook oWB = oXL.Workbooks.Add();
    oWB.SaveAs("C:\Users\konanki\Documents\Sample.xlsm", XlFileFormat.xlOpenXMLWorkbookMacroEnabled, AccessMode: XlSaveAsAccessMode.xlNoChange);
    oWB.Close(true);
}