Microsoft office interop word как подключить

Установлена 13 студия максимальная, хочу добавить в проект ссылку на пакет Microsoft.Office.Interop.Word, но его там нету.

Весь пакет офиса 2007 установлен на компе.

Вопрос
Где искать этот пакет и как потом его добавлять, чтобы он отображался в ссылках добавляемых пакетов

задан 8 мар 2017 в 15:16

unnamed's user avatar

Правый клик на References —> Add Reference, затем перейти на вкладку COM, в поле поиска для Excel вбить Microsoft Excel.

ответ дан 8 мар 2017 в 15:39

sp7's user avatar

sp7sp7

5,2593 золотых знака20 серебряных знаков37 бронзовых знаков

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.

Create New Project in Visual Studio

  • 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.

Configure Visual Studio Projects

  • 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.

Configure VS Projects

  • 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:

C# Interop Objects Tutorial

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.

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!

RRS feed

  • Remove From My Forums
  • Question

  • I have read a lot way to solve this problem, but still can’t find it.

    My pc is win10 & visual studio 2017.

    I can find it in the C:Windowsassembly. Does it means I have installed?

Answers

  • Did you install the Visual Studio Tools for Office?

    — Wayne

    • Marked as answer by
      Chien-Wei
      Thursday, September 13, 2018 4:18 AM

All replies

  • Hi,

    .net 4.0 or later version added reference, if it is not 4.0 or above, there may not be this, you can download a Microsoft.Office.Interop.Word.dll by yourself.

    In your project, right-click on «References» and select «Add» .

    Imports Microsoft.Office.Interop.Word

    Best Regards,

    Alex


    MSDN Community Support Please remember to click «Mark as Answer» the responses that resolved your issue, and to click «Unmark as Answer» if not. This can be beneficial to other community members reading this thread. If you have any
    compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    • Marked as answer by
      Chien-Wei
      Wednesday, September 12, 2018 11:50 AM
    • Unmarked as answer by
      Chien-Wei
      Wednesday, September 12, 2018 11:50 AM

  • With VS 2015, Office 2016, I add the Object Library :

  • There are times when an assembly will not show up and you need to browse for them. Browse under were the bold parts reflect which version of Office is installed.

    C:Program Files (x86)Microsoft Visual Studio 14.0Visual Studio Tools for OfficePIAOffice15.

    You can also add them to «Custom Component Set» in Object Browser (the default hot key is F2). Once added select that library and press the button where the arrow is indicating. 

    I this for all the ones shown as I use them often.


    Please remember to mark the replies as answers if they help and unmark them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via
    my MSDN profile but will not answer coding question on either.
    VB Forums — moderator

    profile for Karen Payne on Stack Exchange, a network of free, community-driven Q&A sites

  • HI,Alex-Li-MSFT

    I check my project is .net4.5.2 , but I can’t find the microsoft.office.interop.word in the VS assemblies.

    Is it any possible that my office is o365 cause the problem?

    Thanks for your reply.

    • Edited by
      Chien-Wei
      Wednesday, September 12, 2018 11:51 AM

  • Hi, Casorix31

    I have add this com already, but there are some code error.

    I try to add a table in the document,but error shows tables are not the member of document.

    I search this problem and they tell me I need to add microsoft.office.interop.word first.

    Thanks for your reply.

    • Edited by
      Chien-Wei
      Wednesday, September 12, 2018 11:52 AM

  • Did you install the Visual Studio Tools for Office?

    — Wayne

    • Marked as answer by
      Chien-Wei
      Thursday, September 13, 2018 4:18 AM

  • Hi, WayneAKing

    Thanks for your help, I finally find it.

  • Hi,

    I am glad you have got your solution, we appreciated you shared us your solution and mark it as an answer.

    Best Regards,

    Alex


    MSDN Community Support Please remember to click «Mark as Answer» the responses that resolved your issue, and to click «Unmark as Answer» if not. This can be beneficial to other community members reading this thread. If you have any
    compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

Задача: вывести данные в документ Word. На самом деле это очень большая и необъятная тема, примерно как сам Word, 90% возможностей которого не используются обычными пользователями. Сузим до более простой и чаще встречающейся на практике задачи, с которой в своей время пришлось столкнуться мне самому: надо вывести красивую справку, договор, отчет или иной документ Word с добавлением данных из кода C#. Само собой должны поддерживаться версии Word до 2007, так что о новых форматах файлов придется забыть.

Для начала вспомним, что в Word есть такая замечательная вещь как шаблоны. Соответственно большую часть сложного оформления можно вынести в них и из кода открывать шаблон и вставлять данные в нужные места. Для начала ограничимся простыми строками (типовая задача в крупных предприятиях — вставка дат, цифр, фио и тому подобных вещей, договор на сумму такую-то, от такой-то даты с фио таким-то с параметрами объекта такими-то).

Задача на текущую статью: открыть из кода C# шаблон Word и что-то в него вставить. Шаблон в формате .dot приготовим заранее, в том же самом ворде. Для связи с ним будем использовать механизм COM Interoperability (сокращенно Interop), то есть запускать отдельный exe-процесс самого Word и через специальный интерфейс управлять им. Интерфейсы слава богу есть и находятся они в специальных библиотеках, поставляемых вместе с Office, но документация по ним крайне невнятная, поведение местами очень странное и не логичное. В версиях Visual Studio 2010 и выше возможности программирования Office расширены, но текущее руководство действительно и для 2008 студии.

Нам надо

1. Подключить нужные библиотеки
2. Открыть шаблон Word
3. Найти в нем нужное место
4. Вставить в него строку с информацией

1. Проект в студии у нас уже должен быть. В разделе Ссылки/References кликаем правой кнопкой, идем в «Добавить ссылку» и ищем Microsoft.Office.Interop.Word. В параметрах добавленной библиотеки ставим true в Копировать локально/Copy local, так как библиотеку надо копировать вместе с исполняемыми файлами проекта.

В код добавляем соответствующие using

using Word = Microsoft.Office.Interop.Word;
using System.Reflection;

2. Теперь вам предстоит провести много времени с замечательным интерфейсом Word, который представляет сам текстовый редактор и его потроха в виде разнообразных обьектов. Сейчас важны два — Application и Document. Переменные для них по ряду не очевидных причин лучше объявлять через интерфейсы.

Word._Application application;
Word._Document document;

Так же почти все функции Word требуют объектных параметров, даже если внутри них сидят простые строки и логические значения, так что лучше заранее сделать несколько оберток

Object missingObj = System.Reflection.Missing.Value;
Object trueObj = true;
Object falseObj = false;

Чтобы запустить Word и открыть в нем шаблон с диска (путь известен), потребуется примерно такой код

//создаем обьект приложения word
application = new Word.Application();
// создаем путь к файлу 
Object templatePathObj = "путь к файлу шаблона";;

// если вылетим не этом этапе, приложение останется открытым
try
{
    document = application.Documents.Add(ref  templatePathObj, ref missingObj, ref missingObj, ref missingObj);
}
catch (Exception error)
{
    document.Close(ref falseObj, ref  missingObj, ref missingObj);
    application.Quit(ref missingObj, ref  missingObj, ref missingObj);
    document = null;
    application = null;
    throw error;
}
_application.Visible = true;

Принципиально важны два момента

1. Мы создаем неуправляемый ресурс, который не соберет сборщик мусора — отдельный процесс в памяти с приложением Word, если мы его не закроем и не выведем на экран, он так и останется там висеть до выключения компьютера. Более того такие ворды могут накапливаться незаметно для пользователя, программист-то еще прибьет их вручную. Заботиться о высвобождения неуправляемого ресурса должен программист.

2. По умолчанию Word запускается невидимым, на экран его выводим мы.

Для начала рассмотрим самый простой и примитивный вариант — поиск и замена строки в документе Word. Некоторые программисты так и работают — ставят в шаблон текстовую метку вроде @@nowDate и заменяют ее на нужное значение.

Пришло время познакомится с фундаментом работы с Word — великим и ужасным объектом Range. Его суть сложно описать словами -это некоторый произвольный кусок документа, диапазон (range), который может включать в себя все что угодно — от пары символов, до таблиц, закладок и прочих интересных вещей. Не стоит путать его с Selection — куском документа, выделенным мышкой, который само собой можно конвертировать в Range. Соотвественно нам надо получить Range для всего документа, найти нужную строку внутри него, получить Range для этой строки и уже внутри этого последнего диапазона заменить текст на требуемый. И не стоит забывать, что документ может иметь сложную структуру с колонтитулами и прочей ересью, возможный универсальный метод для замены всех вхождений данной строки:

// обьектные строки для Word
object strToFindObj = strToFind;
object replaceStrObj = replaceStr;
// диапазон документа Word
Word.Range wordRange;
//тип поиска и замены
object replaceTypeObj;
replaceTypeObj = Word.WdReplace.wdReplaceAll; 
// обходим все разделы документа
for (int i = 1; i <= _document.Sections.Count; i++)
{
    // берем всю секцию диапазоном
    wordRange = _document.Sections[i].Range;

    /*
    Обходим редкий глюк в Find, ПРИЗНАННЫЙ MICROSOFT, метод Execute на некоторых машинах вылетает с ошибкой "Заглушке переданы неправильные данные / Stub received bad data"  Подробности: http://support.microsoft.com/default.aspx?scid=kb;en-us;313104
    // выполняем метод поиска и  замены обьекта диапазона ворд
    wordRange.Find.Execute(ref strToFindObj, ref wordMissing, ref wordMissing, ref wordMissing, ref wordMissing, ref wordMissing, ref wordMissing, ref wordMissing, ref wordMissing, ref replaceStrObj, ref replaceTypeObj, ref wordMissing, ref wordMissing, ref wordMissing, ref wordMissing);
    */

    Word.Find wordFindObj = wordRange.Find;
    object[] wordFindParameters = new object[15] { strToFindObj, _missingObj, _missingObj, _missingObj, _missingObj, _missingObj, _missingObj, _missingObj, _missingObj, replaceStrObj, replaceTypeObj, _missingObj, _missingObj, _missingObj, _missingObj };

    wordFindObj.GetType().InvokeMember("Execute", BindingFlags.InvokeMethod, null, wordFindObj, wordFindParameters);
}

Редкий глюк подробно описан здесь.

На самом деле это не самый лучший метод для вставки информации в документ, так как могут возникнуть сложности с уникальными именами для текстовых меток (если текст одной входит в начало другой, данный метод найдет ее и заменит), их совпадением с произвольным текстом и так далее.

Даже если нам надо найти (и например отформатировать) именно строку с текстом внутри документа, лучше всего выдать наружу найденный Range и уже с ним производить разные злодеяния. Получим примерно такой метод:

object stringToFindObj = stringToFind;
Word.Range wordRange;
bool rangeFound;

//в цикле обходим все разделы документа, получаем Range, запускаем поиск
// если поиск вернул true, он долже ужать Range до найденное строки, выходим и возвращаем Range
// обходим все разделы документа
for (int i = 1; i <= _document.Sections.Count; i++)
{
    // берем всю секцию диапазоном
    wordRange = _document.Sections[i].Range;

    /*
    // Обходим редкий глюк в Find, ПРИЗНАННЫЙ MICROSOFT, метод Execute на некоторых машинах вылетает с ошибкой "Заглушке переданы неправильные данные / Stub received bad data"  Подробности: http://support.microsoft.com/default.aspx?scid=kb;en-us;313104
    // выполняем метод поиска и  замены обьекта диапазона ворд
    rangeFound = wordRange.Find.Execute(ref stringToFindObj, ref wordMissing, ref wordMissing, ref wordMissing, ref wordMissing, ref wordMissing, ref wordMissing, ref wordMissing, ref wordMissing, ref wordMissing, ref wordMissing, ref wordMissing, ref wordMissing, ref wordMissing, ref wordMissing);
    */

    Word.Find wordFindObj = wordRange.Find;

    object[] wordFindParameters = new object[15] { stringToFindObj, _missingObj, _missingObj, _missingObj, _missingObj, _missingObj, _missingObj, _missingObj, _missingObj, _missingObj, _missingObj, _missingObj, _missingObj, _missingObj, _missingObj };

    rangeFound = (bool)wordFindObj.GetType().InvokeMember("Execute", BindingFlags.InvokeMethod, null, wordFindObj, wordFindParameters);

    if (rangeFound) { return wordRange; }
}

// если ничего не нашли, возвращаем null
return null;

Простейшее решение проблемы уникальности текста (нужно нам найти Range слова Word, но внутри всего документа оно встречается десятки раз) — искать строку внутри строки, сначала найти уникальную строку, потом не уникальную внутри нее, неэстетично, но дешево, надежно и практично.

// оформляем обьектные параметры
object stringToFindObj = stringToFind;
bool rangeFound;

/*
Обходим редкий глюк в Find, ПРИЗНАННЫЙ MICROSOFT, метод Execute на некоторых машинах вылетает с ошибкой "Заглушке переданы неправильные данные / Stub received bad data" 
http://support.microsoft.com/default.aspx?scid=kb;en-us;313104
rangeFound = containerRange.Find.Execute(ref stringToFindObj, ref wordMissing, ref wordMissing, ref wordMissing, ref wordMissing, ref wordMissing, ref wordMissing, ref wordMissing, ref wordMissing, ref wordMissing, ref wordMissing, ref wordMissing, ref wordMissing, ref wordMissing, ref wordMissing);
*/

Word.Find wordFindObj = containerRange.Find;

object[]  wordFindParameters = new object[15] { stringToFindObj, _missingObj, _missingObj, _missingObj, _missingObj, _missingObj, _missingObj, _missingObj, _missingObj, _missingObj, _missingObj, _missingObj, _missingObj, _missingObj, _missingObj };

rangeFound = (bool)wordFindObj.GetType().InvokeMember("Execute", BindingFlags.InvokeMethod, null, wordFindObj, wordFindParameters);

if (rangeFound) { return containerRange; }
else { return null; }

Если строку надо просто заменить, то сойдет простейшее

_range.Text = "Это текст заменит содержимое Range";

Но так как Range является универсальный контейнером для любого куска документа Word, то его возможности неизмеримо шире, часть их будет рассмотрена в дальнейших заметках.

Если нам надо просто встать в начало документа (и что-то вставить уже туда):

object start = 0;
object end = 0;
_currentRange = _document.Range(ref start, ref end);

Сохранить документ на диск можно следующим образом

Object pathToSaveObj = pathToSaveString;
_document.SaveAs(ref pathToSaveObj, Word.WdSaveFormat.wdFormatDocument, ref _missingObj, ref _missingObj, ref _missingObj, ref _missingObj, ref _missingObj, ref _missingObj, ref _missingObj, ref _missingObj, ref _missingObj, ref _missingObj, ref _missingObj, ref _missingObj, ref _missingObj, ref _missingObj);
  1. Работаем с MS Word из C#, часть 0, класс и тестовый проект-пример WinForms
  2. Работаем с MS Word из C#, часть 1. Открываем шаблон, ищем текст внутри документа
  3. Работаем с MS Word из C#, часть 2. Вставляем текст на закладку и форматируем
  4. Работаем с MS Word из C#, часть 3. Работа с таблицами
  5. Работаем с MS Word из C#, часть 4. Обьединяем несколько файлов в один, считаем количество страниц
  6. Microsoft.Office.Interop.Word Namespace
  7. Range Interface

Понравилась статья? Поделить с друзьями:
  • Microsoft office interop word words
  • Microsoft office interop word visual studio
  • Microsoft office interop word template
  • Microsoft office interop word tables
  • Microsoft office interop word range