-
README
-
Frameworks
-
Dependencies
-
Used By
-
Versions
This an assembly you can use for Word 2013/2016/2019 COM interop, generated and signed by Microsoft. This is entirely unsupported and there is no license since it is a repackaging of Office assemblies.
Product | Versions |
---|---|
.NET |
net5.0 net5.0-windows net6.0 net6.0-android net6.0-ios net6.0-maccatalyst net6.0-macos net6.0-tvos net6.0-windows net7.0 net7.0-android net7.0-ios net7.0-maccatalyst net7.0-macos net7.0-tvos net7.0-windows |
.NET Core |
netcoreapp2.0 netcoreapp2.1 netcoreapp2.2 netcoreapp3.0 netcoreapp3.1 |
.NET Standard |
netstandard2.0 netstandard2.1 |
.NET Framework |
net20 net35 net40 net403 net45 net451 net452 net46 net461 net462 net463 net47 net471 net472 net48 net481 |
MonoAndroid | monoandroid |
MonoMac | monomac |
MonoTouch | monotouch |
Tizen |
tizen40 tizen60 |
Xamarin.iOS | xamarinios |
Xamarin.Mac | xamarinmac |
Xamarin.TVOS | xamarintvos |
Xamarin.WatchOS | xamarinwatchos |
-
.NETFramework 2.0
- No dependencies.
-
.NETStandard 2.0
- No dependencies.
NuGet packages (28)
Showing the top 5 NuGet packages that depend on Microsoft.Office.Interop.Word:
Package | Downloads |
---|---|
fion.modelerp.core ModelErp |
112.8K |
MyLibery.dll Some useful function. |
16.4K |
WebForms.DocumentViewer WebFormsDocumentViewer is a simple custom control that lets you embed documents (PDF, Word, PowerPoint, Excel, RichTextFormat and Text) in your ASP.NET WebForms pages. |
9.6K |
BalaReva.Word.Activities This package contains the below Activities. |
8.9K |
Ns.Microsoft.Office.Interop.All Microsoft.Office.Interop.All 15.0.0.2 |
7.0K |
GitHub repositories (8)
Showing the top 5 popular GitHub repositories that depend on Microsoft.Office.Interop.Word:
Repository | Stars |
---|---|
greenshot/greenshot Greenshot for Windows — Report bugs & features go here: https://greenshot.atlassian.net or look for information on: |
3.3K |
Tichau/FileConverter File Converter is a very simple tool which allows you to convert and compress one or several file(s) using the context menu in windows explorer. |
2.6K |
saucepleez/taskt taskt (pronounced ‘tasked’ and formely sharpRPA) is free and open-source robotic process automation (rpa) built in C# powered by the .NET Framework |
802 |
telerik/xaml-sdk The XAML SDK is an easy-to-use infrastructure with 1000+ developer focused examples for most of the Telerik WPF and Silverlight controls. |
415 |
MicrosoftTranslator/DocumentTranslator-Legacy Microsoft Document Translator (Archive) — Replaced by the MicrosoftTranslator/DocumentTranslation project in this repository. |
400 |
title | description | ms.custom | ms.date | ms.topic | dev_langs | helpviewer_keywords | author | ms.author | manager | ms.technology | ms.workload | |||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
Office primary interop assemblies |
Learn how to use the primary interop assembly (PIA) to gain access the features of a Microsoft Office application from an Office project. |
devdivchpfy22 |
12/23/2021 |
conceptual |
|
|
John-Hart |
johnhart |
jmartens |
office-development |
office |
Office primary interop assemblies
[!INCLUDE Visual Studio]
To use the features of a Microsoft Office application from an Office project, you must use the primary interop assembly (PIA) for the application. The PIA enables managed code to interact with a Microsoft Office application’s COM-based object model.
[!includeAdd-ins note]
When you create a new Office project, Visual Studio adds references to the PIAs that are required to build the project. In some scenarios, you might need to add references to other PIAs (for example, you can use a feature of Microsoft Office Word in a project for Microsoft Office Excel).
This article describes the following aspects of using the Microsoft Office PIAs in Office projects:
-
Separate primary interop assemblies to build and run projects
-
Use features of multiple Microsoft Office applications in a single project
-
Full list of primary interop assemblies for Microsoft Office applications
For more information about primary interop assemblies, see Primary interop assemblies.
Separate primary interop assemblies to build and run projects
Visual Studio uses different sets of the PIAs on the development computer. These different sets of assemblies are in the following locations:
-
A folder in the program files directory
This set of the assemblies is used when you write code and build projects. Visual Studio installs these assemblies automatically.
-
The global assembly cache
This set of the assemblies is used during some development tasks, such as when you run or debug projects. Visual Studio doesn’t install and register these assemblies; you need to do it yourself.
Primary interop assemblies in the program files directory
The PIAs are automatically added to a location in the file system, outside of the global assembly cache, while you install Visual Studio. When you create a new project, Visual Studio automatically adds references to these copies of the PIAs to your project. Visual Studio uses these copies of the PIAs, instead of the assemblies in the global assembly cache, to resolve type references when you develop and build your project.
When different versions of the PIAs are registered in the global assembly cache, you can face several development issues. The added copies of PIAs will help you to avoid such issues.
For Visual Studio 2017 and later, these copies of the PIAs are installed to following shared locations on the development computer:
-
%ProgramFiles%Microsoft Visual StudioSharedVisual Studio Tools for OfficePIA
-
(or
%ProgramFiles(x86)%Microsoft Visual StudioSharedVisual Studio Tools for OfficePIA
on 64-bit operating systems)
[!NOTE]
For older versions of Visual Studio, these PIAs will be installed to the Visual Studio Tools for OfficePIA folder under the%ProgramFiles%
folder for that version of Visual Studio.
For Example:%ProgramFiles(x86)%Microsoft Visual Studio 14.0Visual Studio Tools for OfficePIA
Primary interop assemblies in the global assembly cache
To perform certain development tasks, the PIAs must be installed and registered in the global assembly cache on the development computer. Typically, the PIAs are installed automatically when you install Office on the development computer. For more information, see Configure a computer to develop Office solutions.
The Office PIAs aren’t required on end-user computers to run Office solutions. For more information, see Design and create Office solutions.
Use features of multiple Microsoft Office applications in a single project
Every Office project template in Visual Studio is designed to work with a single Microsoft Office application. To use features in multiple Microsoft Office applications, or to use features in an application or component that doesn’t have a project in Visual Studio, you must add a reference to the required PIAs.
In most cases, you should add references to the PIAs that are installed by Visual Studio under the %ProgramFiles(x86)%Microsoft Visual StudioSharedVisual Studio Tools for OfficePIA
directory. These versions of the assemblies appear on the Framework tab of the Reference Manager dialog box. For more information, see How to: Target Office applications through primary interop assemblies.
If you’ve installed and registered the PIAs in the global assembly cache, these versions of the assemblies appear on the COM tab of the Reference Manager dialog box. Avoid adding references to these versions of the assemblies, because there are some development issues that can occur when you use them. For example, if you’ve registered different versions of the PIAs in the global assembly cache, your project will automatically bind to the version of the assembly that was registered last, even if you specify a different version of the assembly on the COM tab of the Reference Manager dialog box.
[!NOTE]
Some assemblies are added to a project automatically when an assembly that references them is added. For example, references to theOffice.dll
andMicrosoft.Vbe.Interop.dll
assemblies are added automatically when you add a reference to the Word, Excel, Outlook, Microsoft Forms, or Graph assemblies.
Primary interop assemblies for Microsoft Office applications
The following table lists the primary interop assemblies that are available for [!INCLUDEOffice_16_short], [!INCLUDEOffice_15_short] and [!INCLUDEoffice14_long].
Office application or component | Primary interop assembly name |
---|---|
Microsoft Access 14.0 Object Library
Microsoft Access 15.0 Object Library |
Microsoft.Office.Interop.Access.dll |
Microsoft Office 14.0 Access Database Engine Object Library
Microsoft Office 15.0 Access Database Engine Object Library |
Microsoft.Office.Interop.Access.Dao.dll |
Microsoft Excel 14.0 Object Library
Microsoft Excel 15.0 Object Library |
Microsoft.Office.Interop.Excel.dll |
Microsoft Graph 14.0 Object Library (used by PowerPoint, Access, and Word for graphs)
Microsoft Graph 15.0 Object Library |
Microsoft.Office.Interop.Graph.dll |
Microsoft InfoPath 2.0 Type Library (for InfoPath 2007 only) | Microsoft.Office.Interop.InfoPath.dll |
Microsoft InfoPath XML Interop Assembly (for InfoPath 2007 only) | Microsoft.Office.Interop.InfoPath.Xml.dll |
Microsoft Office 14.0 Object Library (Office shared functionality)
Microsoft Office 15.0 Object Library (Office shared functionality) |
office.dll |
Microsoft Office Outlook View Control (can be used in Web pages and applications to access your Inbox) | Microsoft.Office.Interop.OutlookViewCtl.dll |
Microsoft Outlook 14.0 Object Library
Microsoft Outlook 15.0 Object Library |
Microsoft.Office.Interop.Outlook.dll |
Microsoft PowerPoint 14.0 Object Library
Microsoft PowerPoint 15.0 Object Library |
Microsoft.Office.Interop.PowerPoint.dll |
Microsoft Project 14.0 Object Library
Microsoft Project 15.0 Object Library |
Microsoft.Office.Interop.MSProject.dll |
Microsoft Publisher 14.0 Object Library
Microsoft Publisher 15.0 Object Library |
Microsoft.Office.Interop.Publisher.dll |
Microsoft SharePoint Designer 14.0 Web Object Reference Library | Microsoft.Office.Interop.SharePointDesigner.dll |
Microsoft SharePoint Designer 14.0 Page Object Reference Library | Microsoft.Office.Interop.SharePointDesignerPage.dll |
Microsoft Smart Tags 2.0 Type Library Note: Smart tags are deprecated in [!INCLUDEExcel_14_short] and [!INCLUDEWord_14_short]. | Microsoft.Office.Interop.SmartTag.dll |
Microsoft Visio 14.0 Type Library
Microsoft Visio 15.0 Type Library |
Microsoft.Office.Interop.Visio.dll |
Microsoft Visio 14.0 Save As Web Type Library
Microsoft Visio 15.0 Save As Web Type Library |
Microsoft.Office.Interop.Visio.SaveAsWeb.dll |
Microsoft Visio 14.0 Drawing Control Type Library
Microsoft Visio 15.0 Drawing Control Type Library |
Microsoft.Office.Interop.VisOcx.dll |
Microsoft Word 14.0 Object Library
Microsoft Word 15.0 Object Library |
Microsoft.Office.Interop.Word.dll |
Microsoft Visual Basic for Applications Extensibility 5.3 | Microsoft.Vbe.Interop.dll |
Binding redirect assemblies
When you install and register the Office PIAs in the global assembly cache (either with Office or by installing the redistributable package for the PIAs), the binding redirect assemblies are also installed only in the global assembly cache. These assemblies ensure that the correct version of the primary interop assemblies is loaded at run time.
For example, when a solution that references a [!INCLUDEoffice14_long] assembly runs on a computer that has the [!INCLUDEOffice_15_short] version of the same primary interop assembly, the binding redirect assembly instructs the [!INCLUDEdnprdnshort] runtime to load the [!INCLUDEOffice_15_short] version of the primary interop assembly.
For more information, see How to: Enable and disable automatic binding redirection.
See also
- How to: Target Office applications through primary interop assemblies
- Excel object model overview
- InfoPath solutions
- Outlook object model overview
- PowerPoint solutions
- Project solutions
- Visio object model overview
- Word object model overview
- General reference (Office development in Visual Studio)
- Remove From My Forums
-
Вопрос
-
Приложение windows form C#, VS 2012, подключил сборку Microsoft.Office.Interop.Word, Version=14.0.0.0, у меня на компьютере все работает, а вот на других нет… Почему вылетает такой эксепшион? Может конечно word влияет, у меня 2010
стоит, на других 2007 и 2003. Как можно обойти этот эксепшион?System.IO.FileLoadException: Невозможно загрузить файл или сборку «Microsoft.Office.Interop.Word, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c» или один из зависимых от них компонентов. Найденное определение
манифеста сборки не соответствует ссылке на сборку. (Исключение из HRESULT: 0x80131040)
Имя файла: «Microsoft.Office.Interop.Word, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c»
в Converter.Form1.Form1_Load(Object sender, EventArgs e)
в System.Windows.Forms.Form.OnLoad(EventArgs e)
в System.Windows.Forms.Control.CreateControl(Boolean fIgnoreVisible)
в System.Windows.Forms.Control.CreateControl()
в System.Windows.Forms.Control.WmShowWindow(Message& m)
в System.Windows.Forms.Control.WndProc(Message& m)
в System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
в System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)************** Загруженные сборки **************
mscorlib
Версия сборки: 2.0.0.0
Версия Win32: 2.0.50727.5448 (Win7SP1GDR.050727-5400)
CodeBase: file:///C:/Windows/Microsoft.NET/Framework64/v2.0.50727/mscorlib.dll
—————————————-
Converter
Версия сборки: 1.0.0.0
Версия Win32: 1.0.0.0
CodeBase: file:///F:/Converter.exe
—————————————-
System.Windows.Forms
Версия сборки: 2.0.0.0
Версия Win32: 2.0.50727.5446 (Win7SP1GDR.050727-5400)
CodeBase: file:///C:/Windows/assembly/GAC_MSIL/System.Windows.Forms/2.0.0.0__b77a5c561934e089/System.Windows.Forms.dll
—————————————-
System
Версия сборки: 2.0.0.0
Версия Win32: 2.0.50727.5447 (Win7SP1GDR.050727-5400)
CodeBase: file:///C:/Windows/assembly/GAC_MSIL/System/2.0.0.0__b77a5c561934e089/System.dll
—————————————-
System.Drawing
Версия сборки: 2.0.0.0
Версия Win32: 2.0.50727.5420 (Win7SP1.050727-5400)
CodeBase: file:///C:/Windows/assembly/GAC_MSIL/System.Drawing/2.0.0.0__b03f5f7f11d50a3a/System.Drawing.dll
—————————————-
System.Windows.Forms.resources
Версия сборки: 2.0.0.0
Версия Win32: 2.0.50727.5420 (Win7SP1.050727-5400)
CodeBase: file:///C:/Windows/assembly/GAC_MSIL/System.Windows.Forms.resources/2.0.0.0_ru_b77a5c561934e089/System.Windows.Forms.resources.dll
—————————————-
mscorlib.resources
Версия сборки: 2.0.0.0
Версия Win32: 2.0.50727.5448 (Win7SP1GDR.050727-5400)
CodeBase: file:///C:/Windows/Microsoft.NET/Framework64/v2.0.50727/mscorlib.dll
—————————————-
Ответы
-
Добрый день.
Если установлен Word другой версии, то никак.
Если вы хотите, чтобы ваше приложение работало на любых компьютерах с любыми установленными версиями Office или вообще без них, используйте не Interop, а специальную библиотеку
OpenXML, которая позволяет работать с файлами Officе без самого Office.-
Помечено в качестве ответа
17 июля 2013 г. 7:30
-
Помечено в качестве ответа
-
Еще раз, если вы установите старую версию Word, то на компьютерах, где будет новая версия, все так же будете наблюдать ошибку. Ваша программа будет работать только с той версией Word, под которую вы ее скомпилируете. В этом отношении OpenXml лучше, т.к.
не требует вообще установленного Office ни одной версии. Как всегда у OpenXml есть и обратная сторона, он не может работать с файлами Office ниже чем 2007. Т.е. работа с файлами docx — легко, с файлами doc — нет.Для генерации pdf можно использовать готовую библиотеку. Вот
статья, где приводится о таких библиотеках информация. Посмотрите, может и поможет.-
Помечено в качестве ответа
Ruslan_Gin
17 июля 2013 г. 7:30
-
Помечено в качестве ответа
Table of Contents
- Introducing Interop.Word
- Working with the Document
- Find and Replace Text
- Find and replace Bookmarks
- Convert a DOC / DOCX file to PDF
- Export a DOC / DOCX file into a PDF
- From a Byte Array
If you’re working with ASP.NET C# and you need to open, edit or otherwise access a Microsoft Word DOC or DOCX file, you can easily do that using the Microsoft.Office.Interop.Word library package. This post explains how to do so: you might find it useful in case you need to perform such task or whenever you want to read some insights regarding the process.
Introducing Interop.Word
To access the namespace from your ASP.NET project you have two main choices:
- Install the official Microsoft Office primary interop assemblies (PIAs) package on your machine by downloading and executing the runtime installer, then manually add a Reference to the Microsoft.Office.Interop.Word.dll file.
- Install the appropriate NuGet package within Visual Studio using the Package Manager Console.
Needless to say, you should really go for the second option, but we’ll leave that to you.
Working with the Document
As soon as you have the namespace available, you can do the following:
// NS alias to avoid writing the required namespace all the time using word = Microsoft.Office.Interop.Word; // […] Application app = new word.Application(); Document doc = app.Documents.Open(filePath); |
Once you have the app and the doc objects you can perform a lot of editing task, such as:
Find and Replace Text
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
var textToFind = «any source text»; var textToReplace = «any replacement text»; var matchCase = true; var matchWholeWord = true; var matchWildcards = false; var matchSoundsLike = false; var matchAllWordForms = false; var forward = true; var wrap = 1; var format = false; var replace = 2; app.Selection.Find.Execute( textToFind, matchCase, matchWholeWord, matchWildcards, matchSoundsLike, matchAllWordForms, forward, wrap, format, textToReplace, replace); |
Find and replace Bookmarks
var bookmarkName = «anyName»; var bookmarkNewValue = «anyValue»; if (doc.Bookmarks.Exists(bookmarkName)) { doc.Bookmarks[bookmarkName].Select(); app.Selection.TypeText(bookmarkNewValue); } |
Convert a DOC / DOCX file to PDF
Surprisingly enough, we can even do that with an one-liner thanks to the native «Save As PDF…» feature introduced with Office 2010.
doc.SaveAs2(«path-to-pdf-file.pdf», word.WdSaveFormat.wdFormatPDF); |
Export a DOC / DOCX file into a PDF
This one is almost identical to the previous one in terms of results.
doc.ExportAsFixedFormat(tmpFile, WdExportFormat.wdExportFormatPDF); |
… and so on.
For additional info regarding word-to-pdf conversion, you can also read this dedicated post: otherwise, keep reading.
What if you have the DOC or DOCX file stored outside the FileSystem, such as in blob-format within a Database? If that’s the case you need to use a temporary file, because most Office Interop methods do not support working with byte arrays, streams and so on.
Here’s a decent workaround you can use:
// byte[] fileBytes = getFileBytesFromDB(); var tmpFile = Path.GetTempFileName(); File.WriteAllBytes(tmpFile, fileBytes); Application app = new word.Application(); Document doc = app.Documents.Open(filePath); // .. do your stuff here … doc.Close(); app.Quit(); byte[] newFileBytes = File.ReadAllBytes(tmpFile); File.Delete(tmpFile); |
You might notice that we used the
Close()
method in order to close (and thus save) the file. In case you wan’t to save your changes to the DOC / DOCX file you opened, you need to explicitly say it by adding the
WdSaveOptions.wdDoNotSaveChanges
object parameter in the following way:
doc.Close(word.WdSaveOptions.wdDoNotSaveChanges); |
IMPORTANT: Do not underestimate the call to
app.Quit()
! If you don’t do that, the MS Word instance will be left open on your server (see this thread on StackOverflow for more info on that issue). If you want to be sure to avoid such dreadful scenario entirely you should strengthen the given implementation adding a try/catch fallback strategy such as the follow:
Application app = null; Document doc = null; try { app = new word.Application(); doc = Document doc = app.Documents.Open(filePath); // .. do your stuff here … doc.Close(); app.Quit(); } catch (Exception e) { if (doc != null) doc.Close(); if (app != null) app.Quit(); } |
Unfortunately these objects don’t implement IDisposable, otherwise it would’ve been even easier.
That’s pretty much it: happy coding!
The C# programming language includes capabilities that make working with Microsoft Office API objects easier. With the advent of named and optional arguments, introduction of the dynamic type in .NET, and the ability to pass arguments to the reference parameters in COM methods, C# 4.0 quickly became the language of choice for working with COM and Interop objects.
This article talks about office interop objects in C# and how you can use them to interact with Microsoft Word and Microsoft Excel. Code examples are also provided to illustrate the concepts covered.
Prerequisites for working with Interop Objects
Visual Studio 2019 or Visual Studio 2022 must be installed on your computer to work with the code samples demonstrated in this C# tutorial. In this example, we will be using Visual Studio 2022. If you don’t have it installed in your computer, you can download it from here.
As of this writing, Visual Studio 2022 RC 2 has been released. You should also have Microsoft Office Excel 2007 or Microsoft Office Word 2007 (or their later versions) installed on your computer.
Read: Code Refactoring Tips for C#.
How to Create a New Console Application in Visual Studio
In this section we will examine how we can create a new console application project in Visual Studio 2022. Assuming Visual Studio 2022 is installed on your system, adhere to the steps given below to create a new Console Application project:
- Start the Visual Studio 2022 IDE.
- Click on “Create new project.”
- In the “Create new project” page, select C# in the language drop down list, Windows from the Platforms list and Console from the “Project types” list.
- Select Console App (.NET Framework) from the project templates displayed.
- Click Next.
- In the “Configure your new project” screen, specify the project’s name and the location where you would want the project to be created.
- Before you move on to the next screen, you can optionally select the “Place solution and project in the same directory” checkbox.
- Click Next.
- In the Additional Information screen, specify the Framework version you would like to use. We will use .NET Framework 4.8 in this example.
- Click Create to complete the process.
This will create a new .NET Framework Console application project in Visual Studio 2022. We will use this project in the sections that follow.
Install NuGet Packages
Install the following libraries from NuGet using the NuGet Package Manager or from the NuGet Package Manager Console:
Microsoft.Office.Interop.Word Microsoft.Office.Interop.Excel
Read: Working with C# Math Operators.
How to Program Office Interop Objects in C#
In this section we will examine how to work with Office Interop objects and use them to connect to Microsoft Word and Excel and read/write data.
You must add the following using directives in your program for working with Word and Excel respectively when using Office interop objects:
using Microsoft.Office.Interop.Excel; using Microsoft.Office.Interop.Word;
Working with Excel Interop Objects in C#
To begin, create a new Excel document named Test.xslx as a sample Excel file present in the root directory of the D:> drive. We will use this file in the following example.
You should create an instance of the Application class pertaining to the Microsoft.Office.Interop.Excel library for communicating with Excel. To do this, write the following C# code:
Application excelApplication = new Application();
The next step is to create an instance of the Workbook class to access a Workbook in Excel. You can create an instance of Workbook using the following code:
Workbook excelWorkBook = excel.Workbooks.Open(@"D:Test.xslx");
To read the name of the workbook, you can use the Name property of the workbook instance as shown in the code snippet given below:
string workbookName = excelWorkBook.Name;
The following code listing illustrates how you can display the value of the first cell of the first worksheet of the Excel document:
int worksheetcount = excelWorkBook.Worksheets.Count; if (worksheetcount > 0) { Worksheet worksheet = (Worksheet) excelWorkBook.Worksheets[1]; string worksheetName = worksheet.Name; var data = ((Range) worksheet.Cells[row, column]).Value; Console.WriteLine(data); } else { Console.WriteLine("No worksheets available"); }
Here’s the complete code listing for your reference:
using Microsoft.Office.Interop.Excel; using Microsoft.Office.Interop.Word; using System; using System.Runtime.InteropServices; namespace OfficeInteropDemoApp { class Program { static void Main(string[] args) { string filename = @"D:Test.xlsx"; DisplayExcelCellValue(filename, 1, 1); Console.Read(); } static void DisplayExcelCellValue(string filename, int row, int column) { Microsoft.Office.Interop.Excel.Application excelApplication = null; try { excelApplication = new Microsoft.Office.Interop.Excel.Application(); Workbook excelWorkBook = excelApplication.Workbooks.Open(filename); string workbookName = excelWorkBook.Name; int worksheetcount = excelWorkBook.Worksheets.Count; if (worksheetcount > 0) { Worksheet worksheet = (Worksheet)excelWorkBook.Worksheets[1]; string firstworksheetname = worksheet.Name; var data = ((Microsoft.Office.Interop.Excel.Range) worksheet.Cells[row, column]).Value; Console.WriteLine(data); } else { Console.WriteLine("No worksheets available"); } } catch (Exception ex) { Console.WriteLine(ex.Message); } finally { if (excelApplication != null) { excelApplication.Quit(); Marshal.FinalReleaseComObject(excelApplication); } } } } }
Refer to the code listing given above. Note, the finally block of the DisplayExcelCellValue method. The Quit method is called on the Excel application instance to stop the application. Finally, a call to Marshall.FinalReleaseComObject sets the reference counter of the Excel application instance to 0.
The following code listing illustrates how you can create a new Excel document using Office Interop in C#. Note how a new workbook has been created:
static void CreateExcelDocument() { Microsoft.Office.Interop.Excel.Application excelApplication = null; try { excelApplication = new Microsoft.Office.Interop.Excel.Application(); Workbook excelWorkBook = excelApplication.Workbooks.Add(); Worksheet worksheet = (Worksheet) excelWorkBook.Worksheets[1]; worksheet.Cells[1, 1] = "Product Id"; worksheet.Cells[1, 2] = "Product Name"; worksheet.Cells[2, 1] = "1"; worksheet.Cells[2, 2] = "Lenovo Laptop"; worksheet.Cells[3, 1] = "2"; worksheet.Cells[3, 2] = "DELL Laptop"; excelWorkBook.SaveAs(@"D:Test.xls"); } catch(Exception ex) { Console.WriteLine(ex.Message); } finally { if (excelApplication != null) { excelApplication.Quit(); Marshal.FinalReleaseComObject(excelApplication); } } }
When you run this code, a new Excel document will be created at the path specified with the following content inside:
Read: Working with Strings in C#.
Working with Word Interop Objects in C#
To work with Microsoft Word, you would need to create an instance of Microsoft.Office.Interop.Word.Application. Like Excel, this instance would be used to communicate with a Word document.
Microsoft.Office.Interop.Word.Application wordApplication = new Microsoft.Office.Interop.Word.Application();
The next step is to create a document instance using the Documents property of the Microsoft.Office.Interop.Word.Application instance we just created, as shown in the C# code snippet given below:
wordApplication.Documents.Add();
Next, you can create a paragraph and add some text to it using the as shown in the code snippet shown below:
var paragraph = document.Paragraphs.Add(); paragraph.Range.Text = "This is a sample text to demonstrate how Interop works...";
Then you can save the Word document using this code:
wordApplication.ActiveDocument.SaveAs(@"D:Test.doc", WdSaveFormat.wdFormatDocument);
Here is the complete code listing showing how to work with Microsoft Word Interop Objects in C# for your reference:
using Microsoft.Office.Interop.Excel; using Microsoft.Office.Interop.Word; using System; using System.Runtime.InteropServices; namespace OfficeInteropDemoApp { class Program { static void Main(string[] args) { string filename = @"D:Test.doc"; CreateWordDocument(filename); Console.Read(); } static void CreateWordDocument(string filename) { Microsoft.Office.Interop.Word.Application wordApplication = null; try { wordApplication = new Microsoft.Office.Interop.Word.Application(); var document = wordApplication.Documents.Add(); var paragraph = document.Paragraphs.Add(); paragraph.Range.Text = "This is a sample text to demonstrate how Interop works..."; wordApplication.ActiveDocument.SaveAs(filename, WdSaveFormat.wdFormatDocument); document.Close(); } finally { if (wordApplication != null) { wordApplication.Quit(); Marshal.FinalReleaseComObject(wordApplication); } } } } }
To read a Word document and display each word of the document you can use the following C# code:
static void ReadWordDocument(string filename) { Microsoft.Office.Interop.Word.Application wordApplication = null; try { wordApplication = new Microsoft.Office.Interop.Word.Application(); Document document = wordApplication.Documents.Open(filename); int count = document.Words.Count; for (int i = 1; i <= count; i++) { string text = document.Words[i].Text; Console.WriteLine(text); } } catch(Exception ex) { Console.Write(ex.Message); } finally { if (wordApplication != null) { wordApplication.Quit(); Marshal.FinalReleaseComObject(wordApplication); } } }
Note how the Words property of the Word application instance has been used to retrieve the words contained in the document.
C# Interop Objects Tutorial
In this article we have examined how we can access Microsoft Office Interop objects using C#. Since there is still no support for working with Interop objects in .NET Core, we have created a .NET Framework Console Application in this example.