Trying to exit C# Excel Workbook without a dialog box

╄→гoц情女王★ 提交于 2019-11-30 08:30:07

问题


I am using Microsoft Office Interop to edit some excel files and when I close them I use

outputExcelWorkBook.Close(false, paramMissing, paramMissing);

But a dialog box still comes up, even though I passed false as the first parameter. I have also tried it with true and giving it a file path as the second parameter but in both cases a dialog box comes up asking me if I want to save before closing. Can anyone tell me what's going on here?


回答1:


Try setting the Application.DisplayAlerts property to false. You may find it useful to set this property to false for the majority of your automation routines. Remember to restore the previous value before returning.

Application applicationInstance = ...;
var oldDisplayAlertsValue = applicationInstance.DisplayAlerts;
applicationInstance.DisplayAlerts = false;
try
{
    outputExcelWorkBook.Close(false, Missing.Value, Missing.Value);
}
finally
{
    appliationInstance.DisplayAlerts = oldDisplayAlertsValue;
}



回答2:


This worked for me:

  1. Initiate Excel

  2. Open the workbook

  3. Get the active sheet and make an edit (added "Text" to cell [2,2])

  4. Close the workbook with a single parameter of true which means "save changes"

  5. No dialog box is displayed.

Note: When I call Close without a parameter I am prompted to save changes.

    Microsoft.Office.Interop.Excel.Application excel = new Application();
    Microsoft.Office.Interop.Excel.Workbook workBook =
        excel.Workbooks.Open(fileLocation);
    Microsoft.Office.Interop.Excel.Worksheet sheet = workBook.ActiveSheet;
    sheet.Cells[2, 2] = "Text";
    workBook.Close(true);
    excel.Quit();


来源:https://stackoverflow.com/questions/17413887/trying-to-exit-c-sharp-excel-workbook-without-a-dialog-box

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!