Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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(); 
like image 529
user1546315 Avatar asked Oct 24 '12 18:10

user1546315


People also ask

How can I read Excel file in C# without using Microsoft Office Interop Excel libraries?

Look for GSpread.NET. It's also an OpenSource project and it doesn't require Office installed. You can work with Google Spreadsheets by using API from Microsoft Excel. If you want to re-use the old code to get access to Google Spreadsheets, GSpread.NET is the best way.


1 Answers

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

like image 142
John Bustos Avatar answered Sep 20 '22 20:09

John Bustos