从 C# 桌面应用程序打开以编程方式生成的 Excel 文件时出现 C# 错误:"File format or file extension is not valid"

C# Error while opening programmatically generated Excel file from a C# desktop application: "File format or file extension is not valid"

我正在使用以下代码从使用 Microsoft.Office.Interop.Excel

的 C# WinForms 应用程序生成 Excel .xlsx 文件

截至目前,代码只是创建了一个空白 Excel 文件。 当我尝试打开 xlsx 文件时,出现以下错误。 但是如果我将文件扩展名重命名为 .xls,文件将打开文件。

void WriteData(DataSet ds, string excelFilePath)
{
    Excel.ApplicationClass appExcel = null;
    Excel.Workbooks workbooks = null;
    Excel.Sheets workSheets = null;
    Excel.Workbook wb = null;
    Excel.Worksheet ws = null;
    Excel.Workbook wbTemplate = null;
    Excel.Range range = null;

    try
    {
        appExcel = new Excel.ApplicationClass();
        ExcelUtils.InitExcel(appExcel);
        workbooks = appExcel.Workbooks;
        wb = workbooks.Add(Microsoft.Office.Interop.Excel.XlWBATemplate.xlWBATWorksheet);
        
        wb.SaveAs(excelFilePath, Excel.XlFileFormat.xlWorkbookNormal,
            Missing.Value, Missing.Value, Missing.Value, Missing.Value,
            Excel.XlSaveAsAccessMode.xlNoChange, Missing.Value, Missing.Value, Missing.Value,
            Missing.Value, Missing.Value);
        wb.Close(Type.Missing, Type.Missing, Type.Missing);

    }
    finally
    {
        ExcelUtils.CleanupExcel(appExcel, workbooks, workSheets, wb, ws);
        appExcel = null;
    }
}

我读过其他类似的问题,但其中大部分是使用其他语言或使用某些 Excel 库。 我需要使用 Excel Interop 的解决方案。我不想以 OpenXML 格式保存。

您在保存文件时使用了错误的 XlFileFormat 成员作为您想要的格式。

根据 documentation:

  • xlWorkbookNormal 用于 *.xls 个文件。
  • xlWorkbookDefault 用于 *.xlsx 个文件。

改为传递 Excel.XlFileFormat.xlWorkbookDefault