Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to open an Excel file in C#?

Tags:

c#

.net

excel

vsto

I am trying to convert some VBA code to C#. I am new to C#. Currently I am trying to open an Excel file from a folder and if it does not exist then create it. I am trying something like the following. How can I make it work?

Excel.Application objexcel; Excel.Workbook wbexcel; bool wbexists; Excel.Worksheet objsht; Excel.Range objrange;  objexcel = new Excel.Application(); if (Directory("C:\\csharp\\error report1.xls") = "") {     wbexcel.NewSheet(); }  else {     wbexcel.Open("C:\\csharp\\error report1.xls");     objsht = ("sheet1"); } objsht.Activate(); 
like image 715
tksy Avatar asked Jan 21 '09 11:01

tksy


People also ask

How do I open an Excel spreadsheet in C?

while if you want to open an excel sheet, you click the C folder and type the name of your file in the search bar which is at the top right hand corner of the page. then just click on the file.

Can we read Excel file in C#?

. NET 4+ allows C# to read and manipulate Microsoft Excel files, for computers that have Excel installed (if you do not have Excel installed, see NPOI).


1 Answers

You need to have installed Microsoft Visual Studio Tools for Office (VSTO).

VSTO can be selected in the Visual Studio installer under Workloads > Web & Cloud > Office/SharePoint Development.

After that create a generic .NET project and add a reference to Microsoft.Office.Interop.Excel via 'Add Reference... > Assemblies' dialog.

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

Missing.Value is a special reflection struct for unnecessary parameters replacement


In newer versions, the assembly reference required is called Microsoft Excel 16.0 Object Library. If you do not have the latest version installed you might have Microsoft Excel 15.0 Object Library, or an older version, but it is the same process to include.

enter image description here

like image 89
abatishchev Avatar answered Sep 23 '22 23:09

abatishchev