- Как открыть текстовый документ только для чтения (Open XML SDK) How to: Open a word processing document for read-only access (Open XML SDK)
- Когда рекомендуется открывать документ только для чтения When to Open a Document for Read-only Access
- Создание объекта WordprocessingDocument Create a WordprocessingDocument Object
- Базовая структура документа Basic Document Structure
- Создание разметки WordprocessingML для добавления текста и попытки сохранить текст Generate the WordprocessingML Markup to Add Text and Attempt to Save
- Пример кода Sample Code
Как открыть текстовый документ только для чтения (Open XML SDK) How to: Open a word processing document for read-only access (Open XML SDK)
В этом разделе показано, как использовать классы в пакете Пакет Open XML SDK 2.5 для Office для открытия текстового документа только для чтения программными средствами. This topic describes how to use the classes in the Open XML SDK 2.5 for Office to programmatically open a word processing document for read only access.
Для компиляции кода, представленного в этом разделе, требуются следующие директивы сборки. The following assembly directives are required to compile the code in this topic.
Когда рекомендуется открывать документ только для чтения When to Open a Document for Read-only Access
Иногда требуется открыть документ для проверки или получения некоторых сведений, при этом нужно сделать это так, чтобы документ нельзя было изменить. В этих случаях документ нужно открыть только для чтения. В этом разделе описывается несколько программных способов открытия документа Word в режиме только для чтения. Sometimes you want to open a document to inspect or retrieve some information, and you want to do so in a way that ensures the document remains unchanged. In these instances, you want to open the document for read-only access. This how-to topic discusses several ways to programmatically open a read-only word processing document.
Создание объекта WordprocessingDocument Create a WordprocessingDocument Object
В пакете Open XML SDK класс WordprocessingDocument представляет пакет документов Word. Для работы с документом Word сначала создайте экземпляр класса WordprocessingDocument из документа, а затем работайте с этим экземпляром. После создания экземпляра в документе можно получить доступ к основной части документа, которая содержит текст. Каждый пакет Open XML содержит различные части. Как минимум документ WordProcessingDocument должен содержать основную часть документа, которая выступает как контейнер основного текста документа. Пакет также может содержать дополнительные части. Учтите, что в документе Word текст основной части документа представлен в пакете как XML с использованием разметки WordprocessingML. In the Open XML SDK, the WordprocessingDocument class represents a Word document package. To work with a Word document, first create an instance of the WordprocessingDocument class from the document, and then work with that instance. Once you create the instance from the document, you can then obtain access to the main document part that contains the text of the document. Every Open XML package contains some number of parts. At a minimum, a WordProcessingDocument must contain a main document part that acts as a container for the main text of the document. The package can also contain additional parts. Notice that in a Word document, the text in the main document part is represented in the package as XML using WordprocessingML markup.
Чтобы создать экземпляр класса в документе, нужно вызвать один из методов Open. Представлено несколько таких методов Open с разными сигнатурами. Эти методы позволяют указать, можно ли изменять документ, как описано в следующей таблице. To create the class instance from the document you call one of the Open methods. Several Open methods are provided, each with a different signature. The methods that let you specify whether a document is editable are listed in the following table.
Метод Open Open Method | Раздел справочника по библиотеке классов Class Library Reference Topic | Описание Description |
---|---|---|
Open(String, Boolean) Open(String, Boolean) | Open(String, Boolean) Open(String, Boolean) | Создание экземпляра класса WordprocessingDocument из указанного файла. Create an instance of the WordprocessingDocument class from the specified file. |
Open(Stream, Boolean) Open(Stream, Boolean) | Open(Stream, Boolean) Open(Stream, Boolean) | Создание экземпляра класса WordprocessingDocument из указанного потока ввода-вывода. Create an instance of the WordprocessingDocument class from the specified IO stream. |
Open(String, Boolean, OpenSettings) Open(String, Boolean, OpenSettings) | Open(String, Boolean, OpenSettings) Open(String, Boolean, OpenSettings) | Создание экземпляра класса WordprocessingDocument из указанного файла. Create an instance of the WordprocessingDocument class from the specified file. |
Open(Stream, Boolean, OpenSettings) Open(Stream, Boolean, OpenSettings) | Open(Stream, Boolean, OpenSettings) Open(Stream, Boolean, OpenSettings) | Создание экземпляра класса WordprocessingDocument из указанного потока ввода-вывода. Create an instance of the WordprocessingDocument class from the specified I/O stream. |
В таблице, представленной ранее, указаны только те методы Open, которые принимают логическое значение в качестве второго параметра, определяющее, можно ли изменять документ. Чтобы открыть документ только для чтения задайте в этом параметре значение false. The table above lists only those Open methods that accept a Boolean value as the second parameter to specify whether a document is editable. To open a document for read only access, you specify false for this parameter.
Обратите внимание на то, что два метода Open создают экземпляр класса WordprocessingDocument на основе строки, заданной в качестве первого параметра. Этот способ используется в первом примере кода. В нем применяется первый метод Open из таблицы, представленной ранее, с сигнатурой, для которой требуются два параметра. Первый параметр принимает строку, которая представляет полный путь (для имени файла), из которого требуется открыть документ. Второй параметр имеет значение true или false. В этом примере используется значение false, которое указывает, открывается ли файл для редактирования. Notice that two of the Open methods create an instance of the WordprocessingDocument class based on a string as the first parameter. The first example in the sample code uses this technique. It uses the first Open method in the table above; with a signature that requires two parameters. The first parameter takes a string that represents the full path filename from which you want to open the document. The second parameter is either true or false; this example uses false and indicates whether you want to open the file for editing.
В следующем примере кода вызывается метод Open. The following code example calls the Open Method.
Два других метода Open создают экземпляр класса WordprocessingDocument на основе потока ввода-вывода. Этот подход можно использовать, например, в случае, когда есть приложение Microsoft SharePoint Foundation 2010, которое использует поток ввода-вывода, и для работы с документом необходимо использовать Пакет SDK 2.5 Open XML. The other two Open methods create an instance of the WordprocessingDocument class based on an input/output stream. You might employ this approach, for instance, if you have a Microsoft SharePoint Foundation 2010 application that uses stream input/output, and you want to use the Open XML SDK 2.5 to work with a document.
Следующий пример кода открывает документ на основе потока. The following code example opens a document based on a stream.
Представим, что есть приложение, использующее поддержку Open XML в пространстве имен System.IO.Packaging библиотеки классов .NET Framework, и нужно использовать пакет Пакет SDK 2.5 Open XML для работы с пакетом в режиме доступа только для чтения. В то время как в пакете Пакет SDK 2.5 Open XML есть перегрузки метода, принимающие Package в качестве первого параметра, нет такой перегрузки, которая принимает логическое значение как второй параметр, обозначающее, нужно ли открыть документ для редактирования. Suppose you have an application that employs the Open XML support in the System.IO.Packaging namespace of the .NET Framework Class Library, and you want to use the Open XML SDK 2.5 to work with a package read only. While the Open XML SDK 2.5 includes method overloads that accept a Package as the first parameter, there is not one that takes a Boolean as the second parameter to indicate whether the document should be opened for editing.
Рекомендуется сначала открыть пакет только для чтения перед созданием экземпляра класса WordprocessingDocument, как показано во втором примере кода. В следующем примере выполняется эта операция. The recommended method is to open the package read-only to begin with prior to creating the instance of the WordprocessingDocument class, as shown in the second example in the sample code. The following code example performs this operation.
После открытия пакета документов Word можно получить доступ к основной части документа. Для доступа к телу основной части документа назначьте ссылку на существующее тело документа, как показано в следующем примере. Once you open the Word document package, you can access the main document part. To access the body of the main document part, you assign a reference to the existing document body, as shown in the following code example.
Базовая структура документа Basic Document Structure
Базовая структура документа WordProcessingML состоит из элементов document и body. За ними следуют один или более элементов уровня блока, таких как p, который представляет абзац. Абзац содержит один или несколько элементов r. r означает пробег, область с общим набором свойств, таких как форматирование. Пробег состоит из одного или нескольких элементов t. Элемент t содержит текст. В следующем примере показана разметка WordprocessingML для документа с текстом «Example text». The basic document structure of a WordProcessingML document consists of the document and body elements, followed by one or more block level elements such as p, which represents a paragraph. A paragraph contains one or more r elements. The r stands for run, which is a region of text with a common set of properties, such as formatting. A run contains one or more t elements. The t element contains a range of text. For example, the WordprocessingML markup for a document that contains only the text «Example text.» is shown in the following code example.
Пакет Пакет SDK 2.5 Open XML позволяет создать структуру и содержимое документа с помощью строго типизированных классов, соответствующих элементам WordprocessingML. Эти классы находятся в пространстве имен DocumentFormat.OpenXml.Wordprocessing . В следующей таблице представлены имена классов, соответствующих элементам document, body, p, r и t. Using the Open XML SDK 2.5, you can create document structure and content using strongly-typed classes that correspond to WordprocessingML elements. You will find these classes in the DocumentFormat.OpenXml.Wordprocessing namespace. The following table lists the class names of the classes that correspond to the document, body, p, r, and t elements.
Элемент WordprocessingML WordprocessingML Element | Класс Open XML SDK 2.5 Open XML SDK 2.5 Class | Описание Description |
---|---|---|
document document | Document Document | Корневой элемент основной части документа. The root element for the main document part. |
body body | Body Body | Контейнер для структур уровня блока, таких как абзацы, аннотации, и других, указанных в стандарте ISO/IEC 29500. The container for the block level structures such as paragraphs, tables, annotations, and others specified in the ISO/IEC 29500 specification. |
p p | Paragraph Paragraph | Абзац. A paragraph. |
r r | Run Run | Прогон. A run. |
t t | Text Text | Диапазон текста. A range of text. |
Создание разметки WordprocessingML для добавления текста и попытки сохранить текст Generate the WordprocessingML Markup to Add Text and Attempt to Save
В этом примере кода показано, как можно добавить текст и попытаться сохранить изменения, чтобы обозначить, что документ доступен только для чтения. Так как имеется доступ к основной части документа, текст добавляется посредством добавления экземпляров классов Paragraph, Run и Text. При этом будет создана требуемая разметка WordprocessingML. В следующем примере кода добавляется абзац, пробег и текст. The sample code shows how you can add some text and attempt to save the changes to show that access is read-only. Once you have access to the body of the main document part, you add text by adding instances of the Paragraph, Run, and Text classes. This generates the required WordprocessingML markup. The following code example adds the paragraph, run, and text.
Пример кода Sample Code
В первом примере метод OpenWordprocessingDocumentReadOnly открывает документ Word только для чтения. Вызовите его, передав полный путь к файлу, который нужно открыть. Например, в следующем примере файл Word12.docx в папке «Общие документы» открывается только для чтения. The first example method shown here, OpenWordprocessingDocumentReadOnly, opens a Word document for read-only access. Call it by passing a full path to the file that you want to open. For example, the following code example opens the Word12.docx file in the Public Documents folder for read-only access.
Во втором примере метод OpenWordprocessingPackageReadonly используется для открытия документа Word только для чтения из System.IO.Packaging.Package. Вызовите его, передав полный путь к файлу, который нужно открыть. Например, в следующем примере файл Word12.docx в папке «Public Documents» открывается только для чтения. The second example method, OpenWordprocessingPackageReadonly, shows how to open a Word document for read-only access from a System.IO.Packaging.Package. Call it by passing a full path to the file that you want to open. For example, the following code opens the Word12.docx file in the Public Documents folder for read-only access.
Если вы раскомментируете оператор, который сохраняет файл, программа выдаст IOException, потому что файл открыт только для чтения. If you uncomment the statement that saves the file, the program would throw an IOException because the file is opened for read-only access.
Ниже приведен полный пример кода на языках C# и VB. The following is the complete sample code in C# and VB.