Microsoft Excel can be managed and operated through C# code with the help of several built in libraries, which include functions to operate Excel. In this tutorial, we will show you how to open an excel file in C# application.
Step#1: Create a new project
First of all, let’s start a new project in C#, select Console Application from the options and name the project before hitting the OK button.
Step#2: Accessing Microsoft Office Application Libraries
With that done, the code window will open up. Now we have to add some libraries first. For that, move towards the libraries portion at the top, and add the two assemblies as shown below:
“using Microsoft.Office.Interop”, and
“using Excel=Microsoft.Office.Interop.excel.”
These assemblies contain the functions required for the input and output for Microsoft Office Applications, in this case Excel files in C#.
Step#3: Specifying the path of the Excel file
Next, define a new function in the code, and name it ‘openfile()’. We will be accessing an excel file in C# that already exists in the system. Hence, the function definition will start with a string variable which would contain the path for the excel file we need to open. We can define the path with the “@” sign, enclosing it in double quotes.
Now let us move to the directory where our file is kept. This is the file which has to be opened through our console application. Notice that it only contains a small string over here.
To find its path, you can open up the properties window and move to the security tab. The path is written at the top next to “Object name”. Simply copy and paste it in the code.
Step#4: Finalizing the openfile() Function
With that done, create two more objects, one with the “Excel.workbooks” class and the other with the “Excel.workbook sheet” class. After that, let’s assign the sheet variable in the “books.Open” argument over here.
The function definition is now completed and we just have to call our function. For that, just copy the function name and paste it along with a semicolon in the Main function.
Step#5: Adding References to Execute the Application
If you press F5 to execute the code, you will be notified with some build errors. This is because we haven’t added the references for Microsoft Excel Objects which we are using in our code. To add them, just open the Project menu and choose the “Add Reference” option.
In the “COM” tab, select the component “Microsoft Excel 12.0 Object Library” and press OK.
Now execute the program. A console screen will appear, and after the processing is complete, the excel file will open up.
And this is how to open excel file in C#.