473,385 Members | 1,873 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,385 software developers and data experts.

Problem with closing the C# workbook

Hi,

I am opening a excel file by the C# code and performing some operation and close it. it is working fine.

I am facing problem, when any other excel file is already open, my file open along with that, when i open file through the code.
& doesnt get closed by code, as it happens in normal situation.

If i close it by killing the process, then the file already open is also closed along with that. code is following. Thanks in advance.
Expand|Select|Wrap|Line Numbers
  1. System.Data.DataTable objExcelData;
  2.  
  3.             objM_oExcelApp = new Excel.Application();
  4.  
  5.             objExcelData = new System.Data.DataTable("ExcelData");
  6.  
  7.             objM_oBook = objM_oExcelApp.Workbooks.Open(strFilePath, 0, false, 5, "", "", true, Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, null, null);
  8.  
  9.             objM_oSheet = (Excel._Worksheet)objM_oBook.ActiveSheet;
  10.              .......          
  11.              .......
  12.  
  13.             try
  14.             {
  15.                 objM_oBook.SaveAs(strFilePath, Missing.Value, Missing.Value, Missing.Value,
  16.                     Missing.Value, Missing.Value, xmlSave, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value);
  17.                 objM_oBook.Close(false, false, Missing.Value);
  18.                 objM_oExcelApp.Workbooks.Close();
  19.  
  20.                 System.Runtime.InteropServices.Marshal.ReleaseComObject
  21.                                     (objM_oBook);
  22.                 objM_oBook = null;
  23.  
  24.                 blnReturnValue = true;  
  25.             }
  26.             catch
  27.             {
  28.                 objM_oBook.Close(false, false, Missing.Value);
  29.                 System.Runtime.InteropServices.Marshal.ReleaseComObject
  30.                                     (objM_oBook);
  31.                 objM_oBook = null;
  32.                 blnReturnValue = false;  
  33.             }
  34.  
  35.             objM_oExcelApp.DisplayAlerts = true; 
  36.  
  37.             Program.KillExcelProcess(objM_oExcelApp); 
  38. -----------------------------------------
  39.  [DllImport("user32.dll")] 
  40.         static extern int GetWindowThreadProcessId(int hWnd, out IntPtr lpdwProcessId);
  41.  
  42.  
  43. public static void KillExcelProcess(Excel.Application exl)
  44.         {
  45.             IntPtr processId = default(IntPtr);
  46.             GetWindowThreadProcessId(exl.Hwnd, out processId); 
  47.             Process excelProcess = Process.GetProcessById(processId.ToInt32()); 
  48.             Debug.WriteLine(processId);
  49.             excelProcess.Kill();
  50.         }
  51.  
Jul 16 '09 #1
2 3573
Try to release ALL com objects.
Expand|Select|Wrap|Line Numbers
  1. objM_oBook = objM_oExcelApp.Workbooks.Open(strFilePath, 0, false, 5, "", "", true, Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, null, null); 
Here "Workbooks" is not just a collection, but a COM object which is created when you access it. You need to release it too with ReleaseComObject.

Maybe this little class will help you.

Expand|Select|Wrap|Line Numbers
  1.     public class ComObject<T> : IDisposable
  2.     {
  3.         private T reference;
  4.         private bool disposed;
  5.  
  6.         protected ComObject()
  7.         {
  8.         }
  9.  
  10.         public ComObject(T reference)
  11.         {
  12.             if (reference == null)
  13.                 throw new ArgumentNullException("reference");
  14.  
  15.             this.reference = reference;
  16.         }
  17.  
  18.         public T Reference
  19.         {
  20.             get
  21.             {
  22.                 if (this.disposed)
  23.                     throw new ObjectDisposedException(this.GetType().Name);
  24.  
  25.                 return this.reference;
  26.             }
  27.             protected set
  28.             {
  29.                 if (value == null)
  30.                     throw new ArgumentNullException("value");
  31.  
  32.                 if (this.reference != null && !this.disposed)
  33.                     this.Dispose(true);
  34.  
  35.                 this.reference = value;
  36.  
  37.                 this.disposed = false;
  38.             }
  39.         }
  40.  
  41.         public void Dispose()
  42.         {
  43.             this.Dispose(true);
  44.  
  45.             GC.SuppressFinalize(this);
  46.         }
  47.  
  48.         protected virtual void Dispose(bool disposing)
  49.         {
  50.             if (disposing)
  51.             {
  52.                 if (this.reference != null)
  53.                     Marshal.ReleaseComObject(this.reference);
  54.  
  55.                 this.reference = default(T);
  56.  
  57.                 this.disposed = true;
  58.             }
  59.         }
  60.  
  61.         ~ComObject()
  62.         {
  63.             this.Dispose(false);
  64.         }
  65.     }
  66.  
Expand|Select|Wrap|Line Numbers
  1.             using (ComObject<Excel.IWorkbooks> workbooks = new ComObject<Excel.IWorkbooks>(objM_oExcelApp.Workbooks))
  2.             {
  3.                 //use it through workbooks.Reference
  4.             }
  5.  
Aug 5 '09 #2
Thanks for precious help.
Aug 6 '09 #3

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

Similar topics

5
by: Gary Cobden | last post by:
I have a problem with the following code, which leaves an instance of Excel visible in Task Manager. By a process of elimination I have got it down to the fact that something in the...
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...
1
by: RickH | last post by:
..Cells(1,y).GetType ownly shows instead of .Value, .Copy, etc. The code below is derived from samples, it should work, but I've messed up somewhere... Imports System.Windows.Forms Imports...
4
by: Dries | last post by:
Hello, I am using Excel Interop to export data from a dataset to an excel-file. Everything works fine except closing the excel-file. I have an Application-object and a Workbook-object. I call...
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...
2
by: ridawg | last post by:
Hey, I have some code where I open up Excel then loop through several cases to update several workbooks. Basically something like this (not showing all the code just basic structure). Try...
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): ...
6
by: pleaseexplaintome_2 | last post by:
Help please. The excel instance is removed from task manager when I run the code below. If I uncomment the lines pertaining to a workbook, the instance of excel is not removed from task manager. ...
2
by: GS | last post by:
according to help Dim Obj As New Class1 ' Associate an event handler with an event. AddHandler Obj.Ev_Event, AddressOf EventHandler is the way to go, so I tried oBook = oExcel.Workbooks.Add '...
1
by: fakehitswizard | last post by:
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. string savepath; bool foundPID; int ourPID = 0; int...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
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: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
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: 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...

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.