0
votes

I am using the following code to generate an Excel .xlsx file from a C# WinForms application using Microsoft.Office.Interop.Excel

As of now, the code simply creates a blank Excel file. When I try to open the xlsx file, I get the following error. But if I rename the file extension to .xls, the file opens file.

enter image description here

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;
    }
}

I have read other similar questions but most of them are in other languages or using some Excel library. I need solution using Excel Interop. I do not want to save in OpenXML format.

1

1 Answers

0
votes

You're using the wrong XlFileFormat member for the format you want when you save the file.

According the documentation:

  • xlWorkbookNormal is for *.xls files.
  • xlWorkbookDefault is for *.xlsx files.

Pass Excel.XlFileFormat.xlWorkbookDefault instead.