如何将一个.docx文件的头文件替换为其他.docx文件格式c# [英] how to replace header of one .docx file to other .docx file form c#

查看:209
本文介绍了如何将一个.docx文件的头文件替换为其他.docx文件格式c#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

// Replace header in target document with header of source document.
           using (WordprocessingDocument
               wdDoc = WordprocessingDocument.Open(filepathTo, true))
           {
               MainDocumentPart mainPart = wdDoc.MainDocumentPart;

               // Delete the existing header part.
               mainPart.DeleteParts(mainPart.HeaderParts);

               // Create a new header part.
               DocumentFormat.OpenXml.Packaging.HeaderPart headerPart =
           mainPart.AddNewPart<HeaderPart>();

               // Get Id of the headerPart.
               string rId = mainPart.GetIdOfPart(headerPart);

               // Feed target headerPart with source headerPart.
               using (WordprocessingDocument wdDocSource =
                   WordprocessingDocument.Open(filepathFrom, true))
               {
                   DocumentFormat.OpenXml.Packaging.HeaderPart firstHeader =
           wdDocSource.MainDocumentPart.HeaderParts.FirstOrDefault();

                   wdDocSource.MainDocumentPart.HeaderParts.FirstOrDefault();

                   if (firstHeader != null)
                   {
                       headerPart.FeedData(firstHeader.GetStream());
                   }
               }

               // Get SectionProperties and Replace HeaderReference with new Id.
               IEnumerable<DocumentFormat.OpenXml.Wordprocessing.SectionProperties> sectPrs =
           mainPart.Document.Body.Elements<SectionProperties>();
               foreach (var sectPr in sectPrs)
               {
                   // Delete existing references to headers.
                   sectPr.RemoveAllChildren<HeaderReference>();

                   // Create the new header reference node.
                   sectPr.PrependChild<HeaderReference>(new HeaderReference() { Id = rId });
               }
           }
       }



i使用了上面的代码,但是Image没有从头文件中复制任何帮助..


i used the above code but Image is not copying from header any help..

推荐答案

看到:

http://www.c-sharpcorner.com/UploadFile/Globalking/fileAccessingusingcsharp02242006050207AM/fileAccessingusingcsharp.aspx [ ^ ]

之后可能需要编写更多代码。
See this:
http://www.c-sharpcorner.com/UploadFile/Globalking/fileAccessingusingcsharp02242006050207AM/fileAccessingusingcsharp.aspx[^]
May be you have to write more code afterwards.


这篇关于如何将一个.docx文件的头文件替换为其他.docx文件格式c#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆