Practical phpxlsx

Headers and footers

Introduction

Headers and footers can be added to spreadsheets with the addHeader and addFooter methods.

These two methods place contents in headers and footers in the positions allowed in the XLSX spreadsheets: left, center and right. Contents can be shown in all pages or can be differentiated for the first page and odd and even pages.

Adding headers

The addHeader method adds new headers to the active sheet:

This method includes the following parameters:

  • $contents: array with contents to be added. This array allows three positions for contents: left, center and right
  • $target: first, default and even
  • $options: extra options

For example, to add a new header with text contents in the left, center and right positions:

MS Excel doesn't show headers and footers if the sheet's display mode is not set to pageLayout. The setSheetSettings method from the previous example sets this view type.

Adding images to a header is as simple as with text. Just indicate the 'image' key:

Specific contents such as current page number, total page count, date and hour or name are included with the following special elements: &[Page], &[Pages], &[Date], &[Time], &[Tab], &[File], &[Path].

The following code includes a header with the current page number and the total page count:

Adding footers

The process of adding footers is the same as with headers, but using the addFooter method.

Tips and Tricks

If there is a footer but not a header in a page, the footer content appears behind the cells. In order to bring it to the front it is only necessary to add a header to the page, even if it is a blank one.

It is possible to add empty headers and footers with no text. The header and footer will be available, but without any content.

Methods for replacing contents in headers and footers of XLSX templates are fully explained on Working with templates.

Next - Settings