使用Powershell将页眉和页脚添加到Word文档

时间:2012-05-23 21:12:44

标签: powershell scripting ms-word

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

2 个答案:

答案 0 :(得分:3)

$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部分。

答案 1 :(得分: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);