【问题标题】:Add Headers and Footers to Word Document with Power Shell使用 Powershell 将页眉和页脚添加到 Word 文档
【发布时间】:2022-04-25 20:15:09
【问题描述】:

我正在寻找一种将页眉和页脚插入从 Power Shell 中生成的 Microsoft Word 文档的方法。有没有办法做到这一点?如果是这样,完成此操作所需的一些代码示例是什么?

【问题讨论】:

    标签: powershell scripting ms-word


    【解决方案1】:
    $Document = "c:\temp\tralala.doc" # Must exist
    
    $Word = New-Object -Com Word.Application
    $Word.Visible = $true
    $ExistingDoc = $Word.Documents.Open($document)
    $Selection = $Word.Selection
    $ExistingDoc.ActiveWindow.ActivePane.View.SeekView = 1
    $Selection.TypeText("Here is my automated header")
    $ExistingDoc.ActiveWindow.ActivePane.View.SeekView = 4
    $Selection.TypeText("Here is my automated footer")
    $ExistingDoc.Save()
    $Word.Quit()
    

    有关 SeekView 的可能值列表,请参阅here。 WdSeekView 部分。

    【讨论】:

      【解决方案2】:
      # Create a new Word application COM object
      $Word = New-Object -ComObject Word.Application;
      # Make the Word application visible
      $Word.Visible = $true;
      # Add a new document to the application
      $Doc = $Word.Documents.Add();
      # Get the first Section of the Document object
      $Section = $Doc.Sections.Item(1);
      # Get the header from the Section object
      $Header = $Section.Headers.Item(1);
      # Get the footer from the Section object
      $Footer = $Section.Footers.Item(1);
      
      # Set the text for the header and footer
      $Header.Range.Text = "Hey, I'm the header!";
      $Footer.Range.Text = "Hey, I'm the footer!";
      
      # Create a Table of Contents (ToC)
      $Toc = $Doc.TablesOfContents.Add($Section.Range);
      

      【讨论】:

      • 出于好奇,您列出部分的方式是否可以用于在相同类型的 Power Shell 生成的 Word 文档中生成目录?
      • $Toc = $Doc.TablesOfContents.Add($Section.Range);
      • 很棒的信息。如果有参考资料可以让我多看一些?另外,我将如何在段落和标题中的文本中添加粗体?如何设置文本的水平位置,例如居中、左、右?
      • 我用谷歌搜索这类东西。如果找不到 PowerShell 示例,请搜索 C# 示例并将其翻译成 PowerShell。
      猜你喜欢
      • 2013-03-09
      • 2012-07-25
      • 2018-08-17
      • 1970-01-01
      • 2021-07-21
      • 2014-05-21
      • 2021-08-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多