OpenXml修改word特定内容


采用OpenXml来修改word特定内容,如下:

word:

OpenXml修改word之前:

OpenXml修改word之后:

代码:

 1  string path = @"C:\Users\Administrator\Desktop\新建文件夹 (2)\1.docx";
 2             using (WordprocessingDocument doc = WordprocessingDocument.Open(path, true))
 3             {
 4                 List<Text> textList = new List<Text>();
 5                 Body body = doc.MainDocumentPart.Document.Body;
 6                 foreach (Paragraph paragraph in body.Elements<Paragraph>())
 7                 {
 8                     if (paragraph.InnerText.Contains("河南郑州"))
 9                     {
10                         foreach (Run run in paragraph.Elements<Run>())
11                         {
12                             textList.AddRange(run.Elements<Text>());
13                         }
14                         paragraph.Elements<Run>().FirstOrDefault().Append(new Text("欢迎你,河南郑州!"));
15                     }
16                 }
17                 foreach (Table table in body.Elements<Table>())
18                 {
19                     foreach (TableRow tableRow in table.Elements<TableRow>())
20                     {
21                         foreach (TableCell tableCell in tableRow.Elements<TableCell>())
22                         {
23                             if (tableCell.InnerText.Contains("郑州河南"))
24                             {
25                                 foreach (Paragraph  paragraph in tableCell.Elements<Paragraph>())
26                                 {
27                                     foreach (Run run in paragraph.Elements<Run>())
28                                     {
29                                         textList.AddRange(run.Elements<Text>());
30                                     }
31                                 }
32                                 tableCell.Elements<Paragraph>().FirstOrDefault().Elements<Run>().FirstOrDefault().Append(new Text("欢迎你,河南郑州!"));
33                             }
34                         }
35                     }
36                 }
37                 foreach (var removeText in textList)
38                 {
39                     removeText.Remove();
40                 }
41             }
View Code

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM