The header and footer of a Calc document can be accessed and modified from a page style object. A page style object can be obtained from the document object as shown in the example code below.
In this example, the "Default" page style is used to modify the header and footer. Also note that in a single-sided page document, only the right page header and footer are used, and the left page header and footer are ignored. In a two-sided page document, on the other hand, both the left and right pages need to be edited accordingly.
Also, the header or footer object needs to be re-inserted after it has been modified, or the change will not take effect.
Sub setHeaderAndFooter
oDoc = ThisComponent
oStyles = oDoc.getStyleFamilies().getByName( "PageStyles" )
oPStyle = oStyles.getByName( "Default" )
' Get page number and page count objects.
oPageNumber = oDoc.createInstance( "com.sun.star.text.TextField.PageNumber" )
oPageCount = oDoc.createInstance( "com.sun.star.text.TextField.PageCount" )
oDateTime = oDoc.createInstance( "com.sun.star.text.TextField.DateTime" )
' Edit header
oHeader = oPStyle.RightPageHeaderContent
oHeader.getLeftText().setString( "" )
oHeader.getCenterText().setString( "ABC Company, Inc." )
oCursor = oHeader.getRightText().createTextCursor()
oHeader.getRightText().insertTextContent( oCursor, oDateTime, True )
oPStyle.RightPageHeaderContent = oHeader
' Edit footer
oFooter = oPStyle.RightPageFooterContent
oFooter.getLeftText().setString( "Monthly Report" )
oFooter.getCenterText().setString( "" )
oFooter.getRightText().setString( "Page " )
oCursor = oFooter.getRightText().createTextCursor()
oCursor.gotoEnd( False )
oFooter.getRightText().insertTextContent( oCursor, oPageNumber, True )
oCursor.gotoEnd( False )
oCursor.setString( " of " )
oCursor.gotoEnd( False )
oFooter.getRightText().insertTextContent( oCursor, oPageCount, True )
oPStyle.RightPageFooterContent = oFooter
End Sub