首页 > 技术文章 > WordprocessingDocument Class

ein-key5205 2020-02-25 21:32 原文

https://docs.microsoft.com/zh-cn/dotnet/api/documentformat.openxml.packaging.wordprocessingdocument?view=openxml-2.8.1

定义 WordprocessingDocument-OpenXmlPackage 表示一个 Word 文档。

下面的示例演示如何对现有字处理文档中的第一段应用"标题 3"样式。 要运行的代码示例,请创建字处理文件,并在其中写入一些文本。 运行该代码示例后,检查文件中的文本。 您会注意到第一段的样式,将更改为"标题 3"。

 1 using System;  
 2 using System.Linq;  
 3 using DocumentFormat.OpenXml.Packaging;  
 4 using DocumentFormat.OpenXml.Wordprocessing;  
 5   
 6 namespace WordProcessingEx  
 7 {  
 8     class Program  
 9     {  
10         static void Main(string[] args)  
11         {  
12             // Apply the Heading 3 style to a paragraph.   
13             string fileName = @"C:\Users\Public\Documents\WordProcessingEx.docx";  
14             using ( WordprocessingDocument myDocument = WordprocessingDocument.Open(fileName, true))  
15             {  
16                 // Get the first paragraph.  
17                 Paragraph p = myDocument.MainDocumentPart.Document.Body.Elements<Paragraph>().First();  
18   
19                 // If the paragraph has no ParagraphProperties object, create a new one.  
20                 if ( p.Elements<ParagraphProperties>().Count() == 0 )  
21                     p.PrependChild<ParagraphProperties>(new ParagraphProperties());  
22   
23                 // Get the ParagraphProperties element of the paragraph.  
24                 ParagraphProperties pPr = p.Elements<ParagraphProperties>().First();  
25   
26                 // Set the value of ParagraphStyleId to "Heading3".  
27                 pPr.ParagraphStyleId = new ParagraphStyleId() { Val = "Heading3" };  
28             }  
29             Console.WriteLine("All done. Press a key.");  
30             Console.ReadKey();  
31         }  
32    }  
33 }

 

推荐阅读