472,796 Members | 1,304 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 472,796 software developers and data experts.

C# closing Excel the right way

this is the correct way to close excel with C#. I've seen alot of other bogus posts ALL over the web that don't work, how frustrating.

Expand|Select|Wrap|Line Numbers
  1. string savepath;
  2. bool foundPID; 
  3. int ourPID = 0;
  4. int tmpX = 0;
  5. int indexRow = 1;
  6. int indexCol = 1;
  7. int[] existingPIDs;
  8. existingPIDs = new int[100];
  9.  
  10. // get existing excel processes
  11. Process[] existingExcels = Process.GetProcessesByName("excel");
  12.  
  13.  
  14. savepath = System.Windows.Forms.Application.ExecutablePath.ToString();
  15. savepath = savepath.Substring(0, savepath.LastIndexOf("\\"));
  16. savepath = savepath + "\\Excel-Really-Sucks-Badly.xls";
  17.  
  18. //Excel Application Object
  19. Excel.Application oExcelApp;
  20. Excel.Workbook oExcelWorkbook;
  21. Excel.Worksheet oExcelWorksheet;
  22.  
  23. // build array of already existing excel process IDs
  24. foreach (Process proc in existingExcels)
  25. {
  26.     existingPIDs[tmpX++] = proc.Id;
  27. }
  28.  
  29. // create our new excel app
  30. oExcelApp = new Excel.Application();
  31.  
  32. // build up the list again, this time it should include our new excel app
  33. existingExcels = Process.GetProcessesByName("excel");
  34.  
  35. // find out which of the excel process IDs is our new app
  36. foreach (Process proc in existingExcels)
  37. {
  38.     foundPID = false;
  39.     foreach (int p in existingPIDs)
  40.     {
  41.         if (p == proc.Id)
  42.         {
  43.             foundPID = true;
  44.         }
  45.     }
  46.     if(!foundPID){
  47.         ourPID = proc.Id;
  48.     }
  49. }
  50.  
  51. oExcelApp.DisplayAlerts = false;
  52. oExcelApp.Visible = false;
  53. oExcelWorkbook = oExcelApp.Workbooks.Add(Excel.XlWBATemplate.xlWBATWorksheet);
  54. oExcelWorksheet = (Excel.Worksheet)oExcelWorkbook.Sheets["Sheet1"];
  55.  
  56. oExcelWorksheet.Name = "fakehitswizard.com";
  57.  
  58. // write excel worksheet header
  59. oExcelWorksheet.Cells[indexRow, indexCol] = "I hate Excel";
  60.  
  61. indexRow++;
  62.  
  63. // save excel
  64. oExcelWorkbook.SaveAs(savepath, Excel.XlFileFormat.xlWorkbookNormal, "", "", true, false, Excel.XlSaveAsAccessMode.xlNoChange, false, false, false, false, false);
  65. // close the workbook
  66. oExcelWorkbook.Close(true, savepath, System.Reflection.Missing.Value );
  67. // quit excel 
  68. oExcelApp.Quit();
  69.  
  70. // Unfortunately the above alone should work but it doesn't because microsoft is weak sauce
  71.  
  72.  
  73. Process[] localByName = Process.GetProcessesByName("excel");
  74. // user didnt have any excels open, kill excel
  75. if (tmpX == 0)
  76. {
  77.     foreach (Process proc in localByName)
  78.     {
  79.         proc.Kill();
  80.     }
  81. }
  82. // user does have excel(s) already open, only kill our apps excel
  83. else if (tmpX > 0 && ourPID != 0)
  84. {
  85.     foreach (Process proc in localByName)
  86.     {
  87.         if (proc.Id == ourPID)
  88.         {
  89.             proc.Kill();
  90.         }
  91.     }
  92. }
  93.  
notice none of this Marshal junk, or GC.collect bogus.

try it out, open task manager, start up 0,1,2,3,4,5 or 99 excels, then run your C# app, notice task manager only starts and closes your app's excel, none of the others. Fake Hits Wizard
Oct 11 '07 #1
1 3677
JosAH
11,448 Expert 8TB
Hi, you posted your code solution in the .NET Articles section. Your post isn't
an article (yet): the code needs a bit of explanatory text just to help people to
understand what it's all about.

We can either move your post to the .NET Forum section where everybody can
read it as it is now or we can move your post over to the Editor's Corner where
we can turn your post into a real article. It's up to you. If you don't respond I'll
move your post over to the .NET Forum section.

kind regards,

Jos
Oct 12 '07 #2

Sign in to post your reply or Sign up for a free account.

Similar topics

4
by: federico | last post by:
When I close an excel application opened from a python program with .Close() methood , in tasks manager is still present 'excel.exe' process and if I open manually an excel applicaion I have a...
0
by: Winshent | last post by:
this code opens the workbook.. either protects or unprotects a sheet.. then saves.. so can write to it.. it unprotects then saves fine.. then writes to it no prob.. it resets the password...
2
by: Atley | last post by:
I have written an application that exports data from SQL to Excel. It all works perfectly except that if you open the Task Manager after running my application, there is an instance of Excel in...
0
by: Sania | last post by:
Hi, We have an application that create an excel object on the very beginning of the application: objExcel = New Excel.Application Then I am passing the excel reference to the one of forms...
7
by: rdemyan via AccessMonster.com | last post by:
I want to make sure that I'm closing an opened spreadsheet correctly. I've been having some locking up problems. The following code adds a dummy row to the spreadsheet to ensure that that the data...
0
by: Jono | last post by:
Hello, I've been getting this message when closing excel (not necessarily when closing the workbook by itself, but when closing Excel and the workbook at the same time): ...
1
by: John Bailo | last post by:
I wrote a c# web service that creates an Excel spreadsheet. Even though I follow all the formal procedures for closing the app and finalizing, an instance of Excel still remains in memory. I...
2
by: Ronin85 | last post by:
Hi , I recently have much pain working with excel application especially closing excel . I try several method but with no success i try to urge garbage collector to dispose excel application object,...
2
by: Silgd1 | last post by:
Hi All.... I'm using python 2.4, Win XP Pro v.2002 sp3, and I use pyscripter 1.9.9.2 as my editor. I have written code to open an existing excel file and grab some data. The problem I am...
0
by: erikbower65 | last post by:
Here's a concise step-by-step guide for manually installing IntelliJ IDEA: 1. Download: Visit the official JetBrains website and download the IntelliJ IDEA Community or Ultimate edition based on...
2
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Sept 2023 starting at 18:00 UK time (6PM UTC+1) and finishing at about 19:15 (7.15PM) The start time is equivalent to 19:00 (7PM) in Central...
14
DJRhino1175
by: DJRhino1175 | last post by:
When I run this code I get an error, its Run-time error# 424 Object required...This is my first attempt at doing something like this. I test the entire code and it worked until I added this - If...
0
by: Rina0 | last post by:
I am looking for a Python code to find the longest common subsequence of two strings. I found this blog post that describes the length of longest common subsequence problem and provides a solution in...
5
by: DJRhino | last post by:
Private Sub CboDrawingID_BeforeUpdate(Cancel As Integer) If = 310029923 Or 310030138 Or 310030152 Or 310030346 Or 310030348 Or _ 310030356 Or 310030359 Or 310030362 Or...
0
by: lllomh | last post by:
Define the method first this.state = { buttonBackgroundColor: 'green', isBlinking: false, // A new status is added to identify whether the button is blinking or not } autoStart=()=>{
0
by: lllomh | last post by:
How does React native implement an English player?
0
by: Mushico | last post by:
How to calculate date of retirement from date of birth
2
by: DJRhino | last post by:
Was curious if anyone else was having this same issue or not.... I was just Up/Down graded to windows 11 and now my access combo boxes are not acting right. With win 10 I could start typing...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.