We help IT Professionals succeed at work.

C# Open Excel file

CipherIS
CipherIS asked
on
I am trying to open an excel file in .NET.  I found the below code and I'm trying to use it but I'm receiving errors.  

Application excel = new Application();
Workbook wb = excel.Workbooks.Open(path);

Open in new window


I'm using VS 2015.

Errors I'm receiving are:

1.  Applicaion does not contain a constructor that takes 0 arguments.
2.  Application' does not contain a definition for 'Workbooks' and no extension method 'Workbooks' accepting a first argument of type 'Application' could be found (are you missing a using directive or an assembly reference?)      

I added Interop excel as a reference. v 15.
Comment
Watch Question

Ryan ChongSoftware Team Lead
Commented:
tried use :
System.Diagnostics.Process.Start(path);

Open in new window

?

Author

Commented:
That works.  Just wondering why I can't use the code that I find in my searches.
Top Expert 2016

Commented:
Hi,

Another way to open
        Excel.Application xlApp;
        Excel.Workbook xlWorkBook1;

        xlApp = new Excel.Application();
        xlWorkBook1 = xlApp.Workbooks.Open("c:\\YourFile.xlsx", Type.Missing, false, Type.Missing,
                Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);

Open in new window

REgards

Author

Commented:
The problem is that even when I try
Excel.Application

Open in new window

I still receive an error.  I know I've done this previously in other apps that I've developed.
Éric MoreauSenior .Net Consultant
Top Expert 2016

Commented:
which error?

Author

Commented:
Well, I can't event type "Excel" alone.  When I attempt to intelisense gives me "ExcelDataOnlyFormatOptions".
Senior .Net Consultant
Top Expert 2016
Commented:
you are surely missing the using clauses:
using Microsoft.Office.Core;
using Microsoft.Office.Interop.Excel;

Open in new window

Author

Commented:
I'll look at that.

Author

Commented:
Found the issue.  Another namespace was inadvertently added which negated the Interop.excel namespace.  Thanks Eric.

Author

Commented:
There was code in the namespace similar to

Application = .......;

which was not pointing to excel.  This was causing the problem.

I deleted it.  I should have copied and pasted it here to have as a reference.