0
votes

My c# application exports data to xls files in the following way (the code is provided below, simplified a little as the original one is rather large):

  • ัะพั€ัƒ preformated xls file to a new path;
  • open Excel app;
  • change Excel app options to make it non-interactive;
  • open workbook;
  • write some data inside;
  • save workbook;
  • close workbook;
  • close Excel app.

Everything worked OK with Excel 2007. With Excel 2010 it sometimes hangs on workbook Save() method. No errors, just hangs (as it is waiting for something like dialog).

I could not find any pattern: nearly 1 of 50 calls hangs; the same call being repeated can hang or not hang.

Any thoughts why this can happen?

var app = new Microsoft.Office.Interop.Excel.Application();

app.Visible = false;
app.Interactive = false;
app.ScreenUpdating = false;
app.AlertBeforeOverwriting = false;
app.DisplayFullScreen = false;
app.DisplayFunctionToolTips = false;
app.DisplayInfoWindow = false;
app.AskToUpdateLinks = false;
app.ShowStartupDialog = false;
app.DisplayAlerts = false;
app.UserControl = false;
app.DisplayStatusBar = false;
app.IgnoreRemoteRequests = true;
app.EnableLargeOperationAlert = false;
app.EnableEvents = false;

File.Copy(pathToTemplate, randomTempFileName);

var wb = app.Workbooks.Open
    (randomTempFileName, 3, Missing.Value, Missing.Value, Missing.Value,
    Missing.Value, true, Missing.Value, Missing.Value, Missing.Value,
    Missing.Value, Missing.Value, false, Missing.Value, Missing.Value);

app.Calculation = Microsoft.Office.Interop.Excel.XlCalculation.xlCalculationManual;

for (int i = 1; i <= wb.Sheets.Count; i++)
{
    var ws = (Microsoft.Office.Interop.Excel.Worksheet)wb.Sheets[i];
    try
    {
        ws.EnableCalculation = false;
        // Perform actions to save data into worksheet
    }
    finally
    {
        ws.EnableCalculation = true;
        ComObject.Release(ws);
    }
}

app.Calculation = Microsoft.Office.Interop.Excel.XlCalculation.xlCalculationAutomatic;

wb.Save();
wb.Close(false, Missing.Value, Missing.Value);
ComObject.Release(wb);

var workbooks = app.Workbooks;
foreach (Microsoft.Office.Interop.Excel.Workbook workbook in workbooks)
{
    workbook.Close(false, Missing.Value, Missing.Value);
    ComObject.Release(workbook);
}
ComObject.Release(workbooks);

app.Quit();
ComObject.Release(app);
app = null;
1
Switched from xls to xlsx - nothing changed. - aleyush
Failed to solve the issue with Excel. Switched my code from using Excel Application to EPPlus library, now it works well. - aleyush

1 Answers

0
votes

not sure why this would behave this way , but how about trying out saving sheet by sheet.

it would not have to save lot many sheets at once ?