473,399 Members | 2,146 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,399 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 3937
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: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

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.