Reputation: 158
I create a excel file using C#, and set the ConflictResolution
parameter toExcel.XlSaveConflictResolution.xlLocalSessionChanges
in SaveAs()
function.
I also set the app.UserControl
to false, but the prompt dialog will always show up.
what should I do to disable the dialog
string fileName = "f:\\ok.xlsx";
object missing = Type.Missing;
Excel.Application app = new Excel.Application();
app.Visible = false;
app.UserControl = false;
Excel.Workbook book = app.Workbooks.Add(missing);
Excel.Worksheet sheet = book.ActiveSheet as Excel.Worksheet;
sheet.Name = "s1";
sheet.Cells[1 , 1] = "id";
book.SaveAs(fileName , Excel.XlFileFormat.xlWorkbookDefault ,
missing , missing , missing , missing ,
Excel.XlSaveAsAccessMode.xlNoChange ,
Excel.XlSaveConflictResolution.xlLocalSessionChanges ,
missing , missing , missing , missing);
book.Close(missing , missing , missing);
app.Quit();
Upvotes: 2
Views: 2515
Reputation: 1095
In order to disable Excel's alerts when writing a file, simply use .DisplayAlerts = false;
Example code that I currently use to save my Excel files:
public void SaveExcelFile(Excel.Application app, string exportPath)
{
try
{
//Stops from asking to overwrite
app.DisplayAlerts = false;
Excel._Worksheet sheet = app.ActiveSheet;
//Save and close
sheet.SaveAs(exportPath);
}
catch (Exception ex)
{
//If something fails, show the error
Console.WriteLine("ERROR: Failed to save Excel file! " + ex);
}
finally
{
//Makes sure that there aren't any lingering Excel processes
app.Quit();
}
}
Works like a charm for me. The important part of this snippet is the app.DisplayAlerts = false;
line. This will stop from asking if you want to save the file or overwrite an existing file of the same name. If you aren't wanting to overwrite files automatically in a fear of losing data, then I don't recommend disabling the alerts.
Note: wrapping it all in a try-catch
isn't always the best practice. For the complexity of the program that uses this method, I know where the error may occur (.SaveAs(exportPath);
in case the supplied exportPath
doesn't exist or is a mistype or whatever other reason for it to throw the error). Would probably be best to only wrap the sheet.SaveAs(exportPath);
in the try-catch
just to be certain.
Upvotes: 2