What do i need for that?
- C# IDE (Obviously) If you dont have one, download a C# express version from: http://www.microsoft.com/express/vcsharp/
- Some Office COM components. This gets automatically installed when you install your Microsoft Office 2007/2003 with .Net Programmability Support. If you hadn’t checked that option when you installed the office, go to control panel and change it.
Thats almost it. Now you’re ready start off!
Initializing Environment
Initializing the COM components could be tricky and tiring if you don’t have any prior experiences, but it’s alright, i shall try to make things easy as possible so you get hold of things easily.
- Create a Windows Form Application in the C# new menu. Provide a name and click on ok. A blank form appears in the designer window.
- Now RIGHT click on References folder in your Solution Explorer and click on Add new reference. A new tabbed window opens up with a list of Net, COM and other components. Now select the Office component that you’d like to work with. For eg. if you like to work with WORD, select Microsoft.Office.Interop.Word. For EXCEL, select Microsoft.Office.Interop.Excel and so on.
- Now repeat the same process and under the COM tab, select “Microsoft Office 12.0 Object Library” and click on OK
The code
Starting off with the includes, in the list we add our few lines:
using Microsoft.Office.Core;
using MsWord = Microsoft.Office.Interop.Word;
using PPT = Microsoft.Office.Interop.PowerPoint;
I’ve used MsWord here in ”using MsWord = Microsoft.Office.Interop.Word” to prevent from writing Microsoft.. blah blah every time i create variables. You could use your own variable instead of MsWord. I have been experimenting with Word and PowerPoint files in the code so i’ve included xxx.Word and xxx.PowerPoint. The thing’s basically same with other applications as well.
Next, create an application class.
PPT.ApplicationClass appPowerPoint = null;
PPT.Presentation ppt = null;
Check this out for more info on ApplicationClass.
To open the file, i’ve created a simple function
private void openApplication(string FileName){
appPowerPoint = new PPT.ApplicationClass();
appPowerPoint.Visible = MsoTriState.msoTrue;
ppt = appPowerPoint.Presentations.Open(FileName, MsoTriState.msoTrue, MsoTriState.msoCTrue, MsoTriState.msoCTrue);
}
Oh i forgot to add that this function OPENS AN EXISTING PowerPoint file.
Closing is easy as well.
private void closeApplication(){
ppt.Close();
System.Runtime.InteropServices.Marshal.FinalReleaseComObject(ppt);
ppt = null;appPowerPoint.Quit();
System.Runtime.InteropServices.Marshal.FinalReleaseComObject(appPowerPoint);
appPowerPoint = null;
GC.Collect();
GC.WaitForPendingFinalizers();
}
This the ppt.Close() line just closes the document. Mean the application would still be open. (You can check that out in Task manager). The second paragraph with appPowerPoint.Quit() quits the application.
You could tweak the codes and check other effects by yourself. Good Luck with that
Later.