How to Save/Overwrite existing Excel file with Excel Interop - C#

心不动则不痛 提交于 2019-11-29 06:02:16

问题


Is there a way to save changes to an excel spreadsheet through the excel interop (in this case I am adding a worksheet to it) without having it prompt the user if they want to overwrite the existing file with the changes. I do not want the user to even see the spreadsheet open in my application so having a message box popping up asking them if they want to overwrite the file seems very out of place and possibly confusing to the user.

I am using the workbook.SaveAs(fileloaction) method.

Here is where I am initializing the COM reference objects for the excel interop.

private Excel.Application app = null;
    private Excel.Workbook workbook = null;

    public Excel.Workbook Workbook
    {
        get { return workbook; }
        set { workbook = value; }
    }
    private Excel.Worksheet worksheet = null;
    private Excel.Range workSheet_range = null;

Below is the code I am using to close/save the excel file. The workbook.close() method line is the one that is reportedly throwing the unhandled exception.

 workbook.Close(true, startForm.excelFileLocation, Missing.Value);
            Marshal.ReleaseComObject(app);
            app = null;
            System.GC.Collect();

回答1:


Basically, all you need is ExcelApp.DisplayAlerts = False - Here's how I do it, though:

ExcelApp.DisplayAlerts = False
ExcelWorkbook.Close(SaveChanges:=True, Filename:=CurDir & FileToSave)

Hope this helps




回答2:


Only this code will Require for stop override alert or Template already in use

ExcelApp.DisplayAlerts = False




回答3:


I know this is an old post, but I wanted to share a way to make this work without causing possible frustration in the future.

First what I do not like about using: ExcelApp.DisplayAlerts = False

Setting this flag will set this property on the excel file, not just in your program. This means that if a user makes changes to the file and closes it (by clicking the X), they will not be prompted to save the file and will cause frustration later. It will also disable any other prompts excel would typically post.

I like checking if the file exists before saving it:

        if (File.Exists(SaveAsName))
        {
            File.Delete(SaveAsName); 
        }


来源:https://stackoverflow.com/questions/13055369/how-to-save-overwrite-existing-excel-file-with-excel-interop-c-sharp

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