tags:

views:

5931

answers:

6

The problem: Loading an excel spreadsheet template. Using the Save command with a different filename and then quitting the interop object. This ends up saving the original template file. Not the result that is liked.

public void saveAndExit(string filename)
{        
    excelApplication.Save(filename);
    excelApplication.Quit();
}

Original file opened is c:\testing\template.xls The file name that is passed in is c:\testing\7777 (date).xls

Does anyone have an answer?

(The answer I chose was the most correct and thorough though the wbk.Close() requires parameters passed to it. Thanks.)

A: 

Have you tried the SaveAs from the Worksheet?

Joel Lucsy
A: 

Rather than using an ExcelApplication, you can use the Workbook object and call the SaveAs() method. You can pass the updated file name in there.

Jason Z
+3  A: 

Excel interop is pretty painful. I dug up an old project I had, did a little fiddling, and I think this is what you're looking for. The other commenters are right, but, at least in my experience, there's a lot more to calling SaveAs() than you'd expect if you've used the same objects (without the interop wrapper) in VBA.

Microsoft.Office.Interop.Excel.Workbook wbk = excelApplication.Workbooks[0];  //or some other way of obtaining this workbook reference, as Jason Z mentioned
wbk.SaveAs(filename, Type.Missing, Type.Missing, Type.Missing,
   Type.Missing, Type.Missing, XlSaveAsAccessMode.xlNoChange, 
            Type.Missing, Type.Missing, Type.Missing, Type.Missing,
   Type.Missing);
wbk.Close();
excelApplication.Quit();

Gotta love all those Type.Missings. But I think they're necessary.

kcrumley
A: 
  1. Ditto on the SaveAs
  2. Whenever I have to do Interop I create a separate VB.NET class library and write the logic in VB. It is just not worth the hassle doing it in C#
Conrad
A: 

I think excelApplication.Quit(); doesn't close the Excel process! How resolve that problem?

Pitacho
A: 

to Pitacho Indeed excelApplication.Quit() doesn't always close the Excel process. The thing that i do i detect the process id and in the end i kill it manually. To detect it's id you get all the process before you create the excelApplication and one just after.

meotever
This should be a comment to Pitacho's post. Please post it and delete this post
abatishchev
i am sorry but i am new on this site. How can i post this on his answer?
meotever