採用OpenXml來修改word特定內容,如下: word: OpenXml修改word之前: OpenXml修改word之後: 代碼: 1 string path = @"C:\Users\Administrator\Desktop\新建文件夾 (2)\1.docx"; 2 using (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