Excel 2010有时会挂起来自c#代码的workbook.Save(),所有内容都适用于Excel 2007

时间:2014-03-03 12:38:32

标签: c# excel excel-2010 export-to-excel

我的c#应用程序以下列方式将数据导出到xls文件(下面提供了代码,简化了一点,因为原始代码相当大):

  • 将预先格式化的xls文件转换为新路径;
  • 打开Excel应用;
  • 更改Excel应用选项以使其成为非交互式;
  • 打开工作簿;
  • 在里面写一些数据;
  • 保存工作簿;
  • 关闭工作簿;
  • 关闭Excel应用

使用Excel 2007,一切正常。使用Excel 2010时,它有时会挂起工作簿Save()方法。没有错误,只是挂起(因为它正在等待对话之类的东西)。

我找不到任何模式:50个电话中有近1个挂起;重复的同一个电话可以挂起或不挂起。

有什么想法会发生这种情况吗?

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 个答案:

答案 0 :(得分:0)

不确定为什么会出现这种情况,但如何尝试逐页保存。

它不必一次保存很多张?