C# .NET - Replace Header of a word document by another document body using c#

Asked By Harish Mady on 19-Jun-13 07:53 AM
Hi guys,

I want to replace header of one doc with body of another document. I am able to replace header of one doc with header of another doc. Please help me out
Robbe Morris replied to Harish Mady on 19-Jun-13 09:32 AM
This makes no sense.  You say you want to be able to do and then follow up with a sentence that says you are able to?
Harish Mady replied to Robbe Morris on 20-Jun-13 01:00 AM
public static void AddHeaderFromTo(string filepathFrom, string filepathTo)
    {
      using (WordprocessingDocument
        wdDoc = WordprocessingDocument.Open(filepathTo, true))
      {
        MainDocumentPart mainPart = wdDoc.MainDocumentPart;
        mainPart.DeleteParts(mainPart.HeaderParts);
        DocumentFormat.OpenXml.Packaging.HeaderPart headerPart =
      mainPart.AddNewPart<HeaderPart>();
 
        string rId = mainPart.GetIdOfPart(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());
          }
        }
 
        IEnumerable<DocumentFormat.OpenXml.Wordprocessing.SectionProperties> sectPrs =
      mainPart.Document.Body.Elements<SectionProperties>();
        foreach (var sectPr in sectPrs)
        {
          sectPr.RemoveAllChildren<HeaderReference>();
          sectPr.PrependChild<HeaderReference>(new HeaderReference() { Id = rId });
        }
      }
    }