简体   繁体   中英

How to disable the prompt dialog when I save the excel file created using C# while conflict occurs?

I create a excel file using C#, and set the ConflictResolution parameter to Excel.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();

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM