【问题标题】:C# Error while opening programmatically generated Excel file from a C# desktop application: "File format or file extension is not valid"从 C# 桌面应用程序打开以编程方式生成的 Excel 文件时出现 C# 错误:“文件格式或文件扩展名无效”
【发布时间】:2020-09-25 20:18:50
【问题描述】:

我正在使用以下代码从使用 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 互操作的解决方案。我不想以 OpenXML 格式保存。

【问题讨论】:

    标签: c# excel xlsx


    【解决方案1】:

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

    根据documentation

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

    改为传递Excel.XlFileFormat.xlWorkbookDefault

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-06-30
      • 2023-01-19
      • 1970-01-01
      • 2020-07-11
      • 2012-12-24
      相关资源
      最近更新 更多