我已经从单词模板创建了一个docx文件,现在我正在访问复制的docx文件,并希望用某些其他数据替换某些文本.
我无法获得关于如何从主要部分访问文本的提示?
任何帮助将是可观的.
以下是我的代码.
private void CreateSampleWordDocument() { //string sourceFile = Path.Combine("D:\\GeneralLetter.dot"); //string destinationFile = Path.Combine("D:\\New.doc"); string sourceFile = Path.Combine("D:\\GeneralWelcomeLetter.docx"); string destinationFile = Path.Combine("D:\\New.docx"); try { // Create a copy of the template file and open the copy File.Copy(sourceFile,destinationFile,true); using (WordprocessingDocument document = WordprocessingDocument.Open(destinationFile,true)) { // Change the document type to Document document.ChangeDocumentType(DocumentFormat.OpenXml.WordprocessingDocumentType.Document); //Get the Main Part of the document MainDocumentPart mainPart = document.MainDocumentPart; mainPart.Document.Save(); } } catch { } }
只是给你想法如何做,请尝试:
原文链接:https://www.f2er.com/xml/292241.htmlusing ( WordprocessingDocument doc = WordprocessingDocument.Open(@"yourpath\testdocument.docx",true)) { var body = doc.MainDocumentPart.Document.Body; var paras = body.Elements<Paragraph>(); foreach (var para in paras) { foreach (var run in para.Elements<Run>()) { foreach (var text in run.Elements<Text>()) { if (text.Text.Contains("text-to-replace")) { text.Text = text.Text.Replace("text-to-replace","replaced-text"); } } } } } }
请注意,文本区分大小写.替换后,文本格式不会更改.希望这可以帮助你.