I am developing c# based application to manipulate excel files. Whenever I write to excel file, the file gets corrupted and nothing appears in it on opening. Also, the next time I am not able to open that file as the application shows the exception. The code goes as below:
private static Microsoft.Office.Interop.Excel.Workbook mWorkBook;
private static Microsoft.Office.Interop.Excel.Sheets mWorkSheets;
private static Microsoft.Office.Interop.Excel.Worksheet mWSheet1;
private static Microsoft.Office.Interop.Excel.Application oXL;
public void WriteResultsToSheet()
{
oXL = new Excel.Application();
oXL.Visible = true;
oXL.DisplayAlerts = false;
mWorkBook = oXL.Workbooks.Open(filePath, 0, false, 5, "", "", false, Excel.XlPlatform.xlWindows, "", true, false, 0, true, false, false);
//Get all the sheets in the workbook
mWorkSheets = mWorkBook.Worksheets;
mWSheet1 = (Excel.Worksheet)mWorkBook.Sheets[sheetName.TrimEnd('$')];
Excel.Range range = mWSheet1.UsedRange;
int colCount = range.Columns.Count;
int rowCount = range.Rows.Count;
for (int index = 1; index <= rowCount; index++)
{
try
{
Console.WriteLine(dataGridViewScript.Rows[index].Cells[4].Value.ToString());
}
catch (NullReferenceException nre)
{
if (nre.Message == "Object reference not set to an instance of an object.")
break;
}
Console.WriteLine(dataGridViewScript.Rows[index].Cells[5].Value.ToString());
}
mWorkBook.SaveAs(filePath, Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookNormal,
Type.Missing, Type.Missing, Type.Missing, Type.Missing, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive,
Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
mWorkBook.Close(Type.Missing, Type.Missing, Type.Missing);
oXL.Quit();
mWSheet1 = null;
mWorkBook = null;
GC.WaitForPendingFinalizers();
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
MessageBox.Show("Results exported successfully.");
}
The exception is as below: COMException was unhandled. Excel cannot open the file because the file format or file extension is not valid. Verify that the file is not corrupt.