为什么我会得到两个不同的SaveAs覆盖提示?

我有两个不同的Excel文件,并做了一些改变。 当我另存为…每个文件被提示确认一个现有的文件和覆盖它的选项。 我知道,我可以用Save()命令完全避免这种情况,但是我想知道为什么会有两种不同的外观覆盖提示?

一切都妥善保存,并没有发生错误。

在我的C#代码中,我使用的是MS Excel 14.0 Object Library版本。 (Excel 2010)
我正在使用的IDE是MS Visual Studio 2015社区。
操作系统是Win 7 x64。 硬件风味AMD。

感谢您的时间。

另存为对话框1:

在这里输入图像说明

另存为对话框2

另存为对话框2

我用来testing这个代码…

using System; using System.Windows.Forms; using Microsoft.Office.Interop.Excel; using Excel = Microsoft.Office.Interop.Excel; namespace SO_Question { public partial class Form1 : Form { public Form1() { InitializeComponent(); EditSaveExcelFiles(); } public static void EditSaveExcelFiles() { object misValue = System.Reflection.Missing.Value; string file1 = @"C:\Users\John\Documents\New Folder\MyExcel.xlsx"; string file2 = @"C:\Users\John\Documents\New Folder\MyExcel2.xlsx"; Excel.Application ExcelApp = new Excel.Application(); Workbook workBook1 = ExcelApp.Workbooks.Open(file1, misValue, misValue, misValue, misValue, misValue, misValue, misValue, misValue, misValue, misValue, misValue, misValue, misValue, misValue); Workbook workBook2 = ExcelApp.Workbooks.Open(file2, misValue, misValue, misValue, misValue, misValue, misValue, misValue, misValue, misValue, misValue, misValue, misValue, misValue, misValue); Worksheet workSheet1 = (Worksheet)workBook1.Worksheets.get_Item("Sheet1"); Worksheet workSheet2 = (Worksheet)workBook2.Worksheets.get_Item("Sheet1"); // do some stuff workSheet1.Cells[1, 1] = "Grazer14"; workSheet2.Cells[1, 1] = "Grazer24"; // Different overwrite dialogs? try { workBook1.SaveAs(file1, Excel.XlFileFormat.xlOpenXMLWorkbook, misValue, misValue, misValue, misValue, Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue); workBook2.SaveAs(file2, Excel.XlFileFormat.xlOpenXMLWorkbook, misValue, misValue, misValue, misValue, Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue); } catch (Exception e) { //when user clicks "No" or "Cancel" //MessageBox.Show("No or Cancel: " + e.StackTrace); } workBook2.Close(true, misValue, misValue); workBook1.Close(true, misValue, misValue); ExcelApp.Quit(); System.Runtime.InteropServices.Marshal.ReleaseComObject(workBook1); System.Runtime.InteropServices.Marshal.ReleaseComObject(workBook2); System.Runtime.InteropServices.Marshal.ReleaseComObject(ExcelApp); } } } 

你在这里看到的是Excel显示的第一个消息框不是主题,而第二个是。 这与您保存的特定文件无关(实际上,您可以保存同一文件两次,仍然可以看到相同的行为)。

解决方法是在保存之前使Excel应用程序可见:

 excelApp.Visible = true; 

这样,Excel用户界面将被正确初始化。 你只是不能指望一个无形的应用程序,以正确地初始化其用户界面 – Excel旨在使用其完整的用户界面或根本没有用户界面。

如果您想避免提示并自动覆盖现有文件,则必须禁用显示警报:

 excelApp.DisplayAlerts = false; workBook1.SaveAs(file1); excelApp.DisplayAlerts = true;