Replace Field in Header&Footer in Word Using Interop

前端 未结 3 1945
抹茶落季
抹茶落季 2020-12-31 08:56

How to replace a \"FIELD\" in the header/footer?

Ex: Word doc file with File Name & Date. in place of file path - [FilePath] instead C://Documents/Location/Filen

3条回答
  •  渐次进展
    2020-12-31 09:39

    Finally after going through the poor documentation about introp.word, got the solution

    // Loop through all sections
    foreach (Microsoft.Office.Interop.Word.Section section in wordDocument.Sections) {
    
        wordDocument.TrackRevisions = false; //Disable Tracking for the Field replacement operation
    
        //Get all Headers
        Microsoft.Office.Interop.Word.HeadersFooters headers = section.Headers;
    
        //Section headerfooter loop for all types enum WdHeaderFooterIndex. wdHeaderFooterEvenPages/wdHeaderFooterFirstPage/wdHeaderFooterPrimary;                          
        foreach (Microsoft.Office.Interop.Word.HeaderFooter header in headers)
        {
            Fields fields = header.Range.Fields;
    
            foreach (Field field in fields)
            {
                if (field.Type == WdFieldType.wdFieldDate)
                {
                    field.Select ();
                    field.Delete ();
                    wordApplication.Selection.TypeText ("[DATE]");
                }
                else if (field.Type == WdFieldType.wdFieldFileName)
                {
                    field.Select ();
                    field.Delete ();
                    wordApplication.Selection.TypeText ("[FILE NAME]");
    
                }
            }
        }
    
        //Get all Footers
        Microsoft.Office.Interop.Word.HeadersFooters footers = section.Footers;
    
        //Section headerfooter loop for all types enum WdHeaderFooterIndex. wdHeaderFooterEvenPages/wdHeaderFooterFirstPage/wdHeaderFooterPrimary; 
        foreach (Microsoft.Office.Interop.Word.HeaderFooter footer in footers)
        {
            Fields fields = footer.Range.Fields;
    
            foreach (Field field in fields)
            {
                if (field.Type == WdFieldType.wdFieldDate)
                {
                    field.Select ();
                    field.Delete ();
                    wordApplication.Selection.TypeText ("[DATE]");
                }
                else if (field.Type == WdFieldType.wdFieldFileName)
                {
                    field.Select ();
                    field.Delete ();
                    wordApplication.Selection.TypeText ("[FILE NAME]");
    
                }
            }
        }
    }
    

提交回复
热议问题