WordprocessingDocument Class
Defines WordprocessingDocument - an OpenXmlPackage represents a Word document.
DocumentFormat.OpenXml.Packaging.OpenXmlPartContainer
DocumentFormat.OpenXml.Packaging.OpenXmlPackage
DocumentFormat.OpenXml.Packaging.WordprocessingDocument
Assembly: DocumentFormat.OpenXml (in DocumentFormat.OpenXml.dll)
The following example shows how to apply the "Heading3" style to the first paragraph in an existing word processing document. To run the code example, create a word-processing file and write some text in it. After you run the code example, examine the text in the file. You would notice that the style of the first paragraph is changed to “Heading3.”
using System; using System.Linq; using DocumentFormat.OpenXml.Packaging; using DocumentFormat.OpenXml.Wordprocessing; namespace WordProcessingEx { class Program { static void Main(string[] args) { // Apply the Heading 3 style to a paragraph. string fileName = @"C:\Users\Public\Documents\WordProcessingEx.docx"; using ( WordprocessingDocument myDocument = WordprocessingDocument.Open(fileName, true)) { // Get the first paragraph. Paragraph p = myDocument.MainDocumentPart.Document.Body.Elements<Paragraph>().First(); // If the paragraph has no ParagraphProperties object, create a new one. if ( p.Elements<ParagraphProperties>().Count() == 0 ) p.PrependChild<ParagraphProperties>(new ParagraphProperties()); // Get the ParagraphProperties element of the paragraph. ParagraphProperties pPr = p.Elements<ParagraphProperties>().First(); // Set the value of ParagraphStyleId to "Heading3". pPr.ParagraphStyleId = new ParagraphStyleId() { Val = "Heading3" }; } Console.WriteLine("All done. Press a key."); Console.ReadKey(); } } }
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
// C:\Program Files\Open XML SDK\V2.0\lib\DocumentFormat.OpenXml.dll
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Wordprocessing;
/// <summary>
/// Returns the paragraphs of a Microsoft Word OpenXML document
/// as a list of strings.
/// </summary>
/// <param name="documentFileName"></param>
/// <returns></returns>
/// <remarks>
/// Requires installing Microsoft Open XML SDK 2.0
/// </remarks>
public static List<string> GetParagraphsAsPlainText(string documentFileName)
{
var paragraphs = new List<string>();
try
{
// Open the file read-only since we don't need to change it.
using (var wordprocessingDocument = WordprocessingDocument.Open(documentFileName, false))
{
paragraphs = wordprocessingDocument.MainDocumentPart.Document.Body
.OfType<Paragraph>()
.Select(p => p.InnerText)
.ToList();
}
}
// *** ADD YOUR OWN Catch LOGIC HERE IF YOU KNOW WHAT'S GOOD FOR YOU!!! ;-)
return paragraphs;
}
- 5/28/2010
- Fred Morrison