22

I tried to follow How to open an Excel file in C# tutorial, i.e. added a reference on the Com tab to Microsoft Office 14.0 Object Library and tried to compile code:

using Excel = Microsoft.Office.Interop.Excel;
//...
Excel.Application xlApp;
Excel.Workbook xlWorkBook;
Excel.Worksheet xlWorkSheet;

xlApp = new Excel.ApplicationClass();//error here
//...

and faced a compile-time error, saying

There is no constructor defined for Microsoft.Office.Interop.Excel.ApplicationClass type.

What am I missing?

horgh
  • 17,918
  • 22
  • 68
  • 123

3 Answers3

39

Try this:

Excel._Application xlApp = new Excel.Application();
Allan Spreys
  • 5,287
  • 5
  • 39
  • 44
  • Well, Office 14 + VS 2010 worked with .NET 3.5 and ApplicationClass. Now with VS 2012, Office 14 only is recognized using .NET 4 and I get the same error that you was having. – Pedro77 May 17 '13 at 21:51
3

Use the following to open it:

xlApp = CreateObject("Excel.Application");

CreateObject creates and returns a reference to a COM object. Documentation may be found here:

http://msdn.microsoft.com/en-us/library/7t9k08y5%28v=vs.71%29.aspx

PeterJ
  • 3,705
  • 28
  • 51
  • 71
  • Just added a reference to the documentation. I haven't tried a method similar to the one you tried, so not sure if it works or not, but I just checked a recent VB.NET project I wrote that works and that's how I went about it. – PeterJ Dec 24 '12 at 02:07
  • +1: Vlad Spreys gave the answer I needed. Nevertheless thank you. – horgh Dec 24 '12 at 02:13
  • No problem, actually just voted his answer up as well, it's probably a cleaner way to go about it even though this method works as well. – PeterJ Dec 24 '12 at 02:14
  • Probably I'll check your sugesstion sometime too:) – horgh Dec 24 '12 at 02:17
3

If you're using C# 4.0 (.NET 4) you can go with much easier syntax

var app = new Application( );

var workbook = app.Workbooks.Open("test.xls");

In regards to var: it makes you job easier cuz C# decides which type to chose and go for. If interested you can read about dynamic and var styles.

Remember that interop prior to C# 4.0 is totally a different phenomenon and how C# used to handle Microsoft objects.

just so you know how different, this is how you should've coded it before C# 4.0 to talk to a Word document.

object fileName = @"WordFile.docx";
object missing = System.Reflection.Missing.Value;
object readOnly = true;
var doc = wordApp.Documents.Open(ref fileName, ref missing, ref readOnly,
ref missing, ref missing, ref missing, ref missing, ref missing,
ref missing, ref missing, ref missing);
Mehrad
  • 4,093
  • 4
  • 43
  • 61
  • 1
    well described why to use **Application()** instead of **ApplicationClass()** here at [link](http://blogs.msdn.com/b/ptorr/archive/2004/02/05/67872.aspx) – Mehrad Aug 29 '13 at 07:04