I want to open an excel file and wait for user to edit and save it, and then i use the data.
I am using this code :
string tempFileName = "test.xlsx"; MemoryStream ms = DocumentFormat.OpenXml.Extensions.SpreadsheetReader.Create(); DocumentFormat.OpenXml.Extensions.SpreadsheetWriter.StreamToFile(tempFileName, ms); var psi = new ProcessStartInfo(tempFileName); var p = new Process(); p.StartInfo = psi; p.Start(); p.WaitForExit(); p.Close(); // use the data
and everything looks ok.
but the problem is, if there is an open excel file before running this block i will have an error on p.WaitForExit(); line which is “Invalid Operation Exception”.
i think the reason is: if there is a already a process named “excel.exe” my code wont create another one to wait for it to be exited, and will merge the processes or something like that.
i can force the user to close all open excel documents and then run this code, or i my self kill excel.exe process and start it again from my code. which i don’t want to use these solutions.
please help me to find a way out!
Thanks a lot
When Excel has a spreadsheet open, Excel maintains a file in the same folder as the spreadsheet, and this file exists for as long as the user has the Excel spreadsheet open. The file name (Excel 2007) is the same as your spreadsheet file name but prefixed with “~$”, simply poll for that file existing or use a FileSystemWatcher on the spreadsheet folder to look for it disappearing – this indicates the user has ceased using the spreadsheet and closed it.
Way too late to help out the OP this time obviously, but hopefully this will help someone out in the future. In my case, using the accepted answer (with the “~$” in the file name) seemed a little problematic, if functional. As an alternative, you just need to set the ProcessStartInfo.FileName to “EXCEL.EXE” and give it the file path as an argument.
var psi = new ProcessStartInfo() psi.FileName = "EXCEL.EXE"; psi.Arguments = tempFileName; var p = new Process(); p.StartInfo = psi; p.Start(); p.WaitForExit(); p.Close();
Works fine for me (with Excel 2013, at least) when instances of Excel are already open, etc. Your experience may vary, depending on your version of Excel.