Lets say I have an Excel file named "DataSheet.xls" open. How can I kill that Excel file using c#?
using Excel = Microsoft.Office.Interop.Excel;
(...)
var app = (Excel.Application)System.Runtime.InteropServices.Marshal.GetActiveObject("Excel.Application");
// I have english excel, but another culture and need to use english culture to use excel calls...
Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo("en-US");
app.Workbooks["DataSheet"].Close(false, false, false);
It's very likely that a single process will contain multiple open workbooks. Especially because Excel prefers to re-use an existing instance when opening files from Explorer, Outlook, etc. instead of creating a new process for each workbook.
Not to mention killing the process will require you to either 1) close the main window which will prompt if there's unsaved changes or 2) forcefully kill the process which will likely cause Excel to show its crash recovery options the next time you launch it.
The best course of action is to use the Excel COM API to close the workbooks. You can use the Marshal.GetActiveObject method to get a running instance of Excel and then refer to the Office developer reference for more information about how to close specific named workbooks without prompting.
The Process class would allow you to kill a process. You could inspect all running excel.exe processes, get the main window handle for the process, check whether the caption of that window contains the name of the XLS file and then kill the process for that window.
Otherwise you could use the Office COM classes to talk to Excel. This may also allow you to shut down open workbooks.
off hand don't have the code as such. but generally, in the past i'd have used a couple of api calls to do this. first, you'd get the window handle (hWnd) and then you'd use the sendmessage api call with the wm_close parameter.
that's about all i can remember -it's been about 10 yrs since i had to do that kinda stuff, so the field may have changed since then :)
Related
I have a C# ExcelDna XLL function library that I register during startup from a VSTO add-in.
this.Application.RegisterXLL(xllPath);
When I shell execute an Excel file (Process.Start the .xlsx file) then most of the time everything works and the functions evaluate when the workbook opens.
When opening the workbook in this manner Excel reuses a currently running EXCEL.EXE process if one exists. Most of the time this is fine, but under certain conditions, for example if Excel was opened through COM and then closed, then when the Excel instance is closed, it doesn't really close, but instead shuts down all of its add-ins and unregisters all XLLs but remains alive. When process invoking into one of these zombie processes the functions, obviously, no longer evaluate.
To attempt to get around this I have tried to open Excel directly, using the .xlsx file as a command line parameter, but in this case there seems to be some kind of race condition and the workbook opens before the XLL has finished registering and the functions always evaluate as #NAME. If the cell is modified and reevaluated then the function correctly evaluates. Calling Application.CalculateFull() and all possible variations has no effect.
If I open a file via Explorer (i.e. double clicking on it) then strangely it now returns #N\A rather than #NAME but still it is the same problem.
I've even tried registering the XLL so it loads on start-up (see here) and it still doesn't work.
Has anyone else encountered this and found a reliable way to get XLL functions to evaluate when opening an Excel instance?
We've found that, if the Add-In isn't loaded properly and the functions don't calculate, performing a global search and replace (e.g. search for = replace with =) forces a recalc when the regular recalc doesn't work. You could potentially automate this with VBA Application.OnTime
The problem I am having involves saving a workbook that is created in C# code on a clients machine. The published version of the program works perfectly on my machine, but not on the clients.
Overview of the Process:
When the program has completed it's iterations it will create worksheets once complete it will save the workbook and display a message box saying that the export was successful and display the workbook that was created.
The Problem:
When ran on the clients machine it will go through the process of creating the worksheets, but for some reason it will not save the file. It dose keep the instance of excel in memory, so when you open task manager you will see the process. Also after you run the program and try to turn off the computer it will prompt you to save or not save the workbook that was created since the instance is still in memory. This is how i have worked around and got to save the workbook to verify that the program did create the worksheets.
My thoughts:
I am thinking that there maybe some settings for windows or for excel that is preventing the excel file to be saved and automatically opened. I am also using background worker to accomplish the task of monitoring the progress of the workbook creation process, so this could also be a problem.
If anyone has encountered this problem or know of a solution please let me know. If more information is needed then i can provide that.
I did not include code, because i did not find it useful in knowing why the problem is happening since everything works on my development machine, but not the clients.
EDIT
I work with Jared and was finally able to debug the program on another machine with VS installed. It turns out that the problem wasn't in the save function at all but with the number of default sheets created on a client machine.
When creating the workbook, the program is supposed to go through the worksheets and delete all of them but the first one. There was a logic flaw (coded by me :/) that would leave an empty sheet in the workbook which caused the problem at this statement:
int lastRow = _excelWorksheet.Cells.Find("*", Type.Missing, Type.Missing, Type.Missing,
XlSearchOrder.xlByRows, XlSearchDirection.xlPrevious, false, Type.Missing, Type.Missing).Row;
Apparently it doesn't like searching for stuff on an empty sheet. Our development machines are currently set to default to one sheet only, so we didn't run into the problem.
What I found odd was that while debugging, the program would throw a System.NullReferenceException at that line. However, the program wouldn't crash on the client machines. Instead, it would just leave the Excel instance in memory as described and would just sit there. As Jared said, the excel stuff runs on a background thread so maybe that has something to do with it.
I have written a C# program which import a product list from a .xlsx file and let the user create an order based on that product list.
When the user is finished, the program builds one or more system specifications based on the order.These specifications is written to a .docx file. I have Office 2007 installed on the computer and are using the Microsoft.Office.Interop.Excel and the Microsoft.Office.Interop.Word namespaces.
The problem:
After I have runned the program, Windows Explorer crashes very often and has to restart. This happens when navigating in folders or when right- clicking on folders etc.
This also happens after the program have been closed and the only solution to make it stop is to restart the computer. It seems like it only happens when I have created the output files (.docx). If i start the program and use it like I normally do, but without creating the word files, the problem don't seem to occur.
After the program have created the output files, Word gets "Visible" to the user for manual editing. The user closes the word application when finished editing the documents.
What can make the Windows Explorer crash when running word automation?
I really need help on this one. Any suggestions are welcome.
After execution, do you have ghost excel.exe and word.exe processes remaining?
These ghost are likely to make the system unstable.
You're likely not releasing properly the COM objects you instantiated via automation.
Use Marshal.ReleaseComObject(yourobj); on each and every COM objects you instantiate. It's a real pain, I know.
Note: be sure that you don't instantiate COM objects without knowing it:
mySheet = myExcelObject.workbooks[0].Sheet[0] won't just instantiate a sheet object, but also a workbook object.
Rule of thumb: never ever use a secondary property on a COM object ( foo.bar.baz ) and release everything.
Final note: don't use office automation at all on the server, it's bad, per Microsoft own words, there are fully managed libraries for that.
My WPF app can open and edit single documents. I am looking for a tidy approach to allow multiple instances of my WPF app to run but to only allow a given document to be open in one instance of the app. If a user tries to open a document which is already opened in another instance, I need to pop up a dialog to tell them and allow them to switch to the other app instance if required.
Thanks
Dan
One approach is to attempt to take an exclusive lock on the file when you open it. When your other application instance attempts to open the file, an IOException will be raised. You can catch this exception and show a dialog to your user stating that the file is already opened in another application. This scenario should be covered anyway, as the file could be open in a different application that is not yours.
I am currently hosting an IE Browser control in a .NET (2.0) Form and using it to load Office files such as Excel and Word thusly:
_ieCtrl.Navigate("C:\\test.xls", False);
The hosting and loading works well except whenever I navigate to a file I am presented with a dialog that asks whether I want to save or open the file. (This is standard IE file-download behavior.) I always want to open it of course and I do not want the dialog to show.
Another issue is that when I close the window that hosts the IE control and the Office doc the document does not close and remains open on disk. This means that subsequent attempts to open the same file via my app or the native office app will fail because of the sharing violation.
Is there a programmatic way of avoiding this dialog and cleaning up resources afterward? I am asking for a programmatic answer because web research has only yielded solutions that entail modifying OS-level settings.
Bounty NOTE:
I am open to any solution to this issue that will allow me to:
Host an Excel spreadsheet inside my application
Work rather transparently (avoid usability issues like the one described above)
Avoid having to make any OS-specific changes that may affect other applications (especially icluding IE)
Is zero additional cost (no licensed 3rd party libs please) Code Project and other open source resources are OK
Not mess around with the DSO Framer ActiveX control, unless a stable version is developed/discovered
Is your intention for the user to be able to work with the Excel file in an Excel-ish way (i.e. columns, rows, formulas, etc.), possibly saving it back? If this is the case, I can't see how you can solve this problem well without relying on COM Interop with the Excel object model or by integrating third-party libraries to work with the Excel sheet. I know you said no paid solutions, but there are some feature-rich 3rd-party controls out there just for working with Excel files within applications.
I noticed in your comment to SLaks that the final product is a "dashboard of sorts". If your intention is to design a a custom dashboard application, have you considered parsing the Excel file(s) to extract the data and then presenting it in a logical manner within your application. This removes the need to directly display and work with the Excel file while still allowing you to work with the data inside that file. If you are trying to get the data outside of the file, here are two approaches among many:
You might consider using the Excel object model and COM interop to read the data from the Excel file into your application. Granted, this includes a dependency on Excel being installed, but it is a possibility. This article has some great code for getting started with reading Excel files in this way.
A better way might be to use a library that doesn't have a dependency on Excel being installed on the local system. This answer suggests using the Excel Data Reader library, available on CodePlex.
I know this answer side-steps your original answer of "hosting MS Office documents in [a] custom app," but in case what you're really interested in is the data inside those Excel files, hopefully this answer will prove helpful.
This is a horrible hack and should only be considered as a last resort: SendKeys.Send("{O}");
http://msdn.microsoft.com/en-us/library/system.windows.forms.sendkeys%28VS.71%29.aspx
Something similar to
_ieCtrl.Navigate("C:\\test.xls", False);
(code to sleep or wait may be needed here)
SendKeys.Send("{O}");
Basically, you send the "o" key to the dialog so it presses the "open" option. You are simulating a keyboard presses to click the "open" button. It is hackey because
1) you may need to wait in between
calls. If you send the o key before
the dialog is up it will be missed.
Hopefully the navigate call is finished when the dialog pops (dont know behavior of control in c#). You may need to experiment with the time since different computers will open faster\slower
2) If the dialog is not shown on a
computer, you will be inserting "o"s
into it. This may cause problems when
exiting because it may popup another dialog to try and save
the changes. May be able to prevent this by opening it in read-only mode
3) Different versions or windows may need different sendkeys commands. For example, you may need to send "o" and them the "{enter}" key
4) Probably more :)
If you want to open the file in a separate Excel instance (not embedded in the WebBrowser control), you can simply call
Process.Start(#"C:\Test.xls");
Office was never meant to run in embedded mode, not in a web page or in an ActiveX Document host. Microsoft had time and time again given us the warning. From pulling dsoframer from the knowledge base to skipping the BrowserFlags registry key in Office 2007.
Move to Office add-ins, Excel Web Access or Office Web Apps as quickly as you can.