尽管没有具有这种格式的可选页眉页码样式,但您可以通过将特定的 MS Word 文档字段、PAGE 和 NUMPAGES 字段添加到页眉(或页脚)或其他位置来实现这一点。
procedure TForm1.MakeDocWithPageNumbers;
var
MSWord,
Document : OleVariant;
AFileName,
DocText : String;
begin
MSWord := CreateOleObject('Word.Application');
MSWord.Visible := True;
Document := MSWord.Documents.Add;
DocText := 'Hello Word!';
MSWord.Selection.TypeText(DocText);
if MSWord.ActiveWindow.View.SplitSpecial <> wdPaneNone then
MSWord.ActiveWindow.Panes(2).Close;
if (MSWord.ActiveWindow.ActivePane.View.Type = wdNormalView) or (MSWord.ActiveWindow.ActivePane.View.Type = wdOutlineView) then
MSWord.ActiveWindow.ActivePane.View.Type := wdPrintView;
MSWord.ActiveWindow.ActivePane.View.SeekView := wdSeekCurrentPageHeader;
MSWord.Selection.TypeText( Text:='Page ');
MSWord.Selection.Fields.Add( Range:= MSWord.Selection.Range, Type:=wdFieldEmpty,
Text:= 'PAGE \* Arabic ', PreserveFormatting:=True);
MSWord.Selection.TypeText( Text:=' of ');
MSWord.Selection.Fields.Add( Range:=MSWord.Selection.Range, Type:=wdFieldEmpty,
Text:= 'NUMPAGES \* Arabic ', PreserveFormatting:=True);
MSWord.Selection.GoTo(What:=wdGoToPage, Which:=wdGoToNext, Count:=1);
AFileName := 'd:\aaad7\officeauto\worddocwithheader.docx';
Document.SaveAs(AFileName);
ShowMessage('Paused');
Document.Close;
end;
我已经将字体大小和右对齐设置为读者的练习,因为 SO 不应该是代码编写服务;=)