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.
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.