簡體   English   中英

如何在發生沖突時保存使用 C# 創建的 excel 文件時禁用提示對話框?

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

我使用 C# 創建了一個 excel 文件,並在SaveAs()函數中將ConflictResolution參數設置為Excel.XlSaveConflictResolution.xlLocalSessionChanges

我還將app.UserControl設置為 false,但提示對話框將始終顯示。

我該怎么做才能禁用對話框

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();

為了在寫入文件時禁用 Excel 的警報,只需使用.DisplayAlerts = false;

我目前用於保存 Excel 文件的示例代碼:

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();
    }
}

對我來說就像一種魅力。 此代碼段的重要部分是app.DisplayAlerts = false; 線。 這將停止詢問您是要保存文件還是覆蓋同名的現有文件。 如果您不想因擔心丟失數據而自動覆蓋文件,那么我不建議禁用警報。

注意:將其全部包裝在try-catch中並不總是最佳實踐。 對於使用此方法的程序的復雜性,我知道可能發生錯誤的位置( .SaveAs(exportPath);以防提供的exportPath不存在或輸入錯誤或任何其他原因引發錯誤)。 最好只包裝sheet.SaveAs(exportPath); try-catch只是為了確定。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM