我已经从单词模板创建了一个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 { } }
现在如何找到某些文字并替换相同?
我无法通过链接,所以一些代码提示将是可观的.
只是给你想法如何做,请尝试:
using ( 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"); } } } } } }
请注意,文本区分大小写.替换后,文本格式不会更改.希望这可以帮助你.
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。