How to Set Different Header or Footer for Odd and Even Pages in Excel in C#, VB.NET

Headers or footers are added to a worksheet to deliver some extra information about each page. By default, the headers or footers on odd and even pages are the same. However, we are able to set different headers or footers for odd and even pages to display different information.

Following sections demonstrate how to create different odd and even page headers/footers using Spire.XLS.

Code Snippet:

Step 1: Initialize an instance of Workbook and get the first worksheet.

Workbook wb = new Workbook();
Worksheet sheet = wb.Worksheets[0];

Step 2: Set the value of DifferentOddEven as 1, which indicates that headers/footers for odd and even pages are different.

sheet.PageSetup.DifferentOddEven = 1;

Step 3: Set header and footer string for odd pages, and format the string.

sheet.PageSetup.OddHeaderString = "&\"Arial\"&12&B&KFFC000Odd_Header";
sheet.PageSetup.OddFooterString = "&\"Arial\"&12&B&KFFC000Odd_Footer";

Step 4: Set different header and footer string for even pages, and format the string with different color.

sheet.PageSetup.EvenHeaderString = "&\"Arial\"&12&B&KFF0000Even_Header";
sheet.PageSetup.EvenFooterString = "&\"Arial\"&12&B&KFF0000Even_Footer";

Step 5: Save the file.

wb.SaveToFile("OddEvenHeaderFooter.xlsx", ExcelVersion.Version2013);

Output:


How to Set Different Header or Footer for Odd and Even Pages in Excel in C#, VB.NET

Full Code:

[C#]
Workbook wb = new Workbook();
Worksheet sheet = wb.Worksheets[0];

sheet.Range["A1"].Text = "Page 1";
sheet.Range["J1"].Text = "Page 2";

sheet.PageSetup.DifferentOddEven = 1;      
sheet.PageSetup.OddHeaderString = "&\"Arial\"&12&B&KFFC000Odd_Header";
sheet.PageSetup.OddFooterString = "&\"Arial\"&12&B&KFFC000Odd_Footer";
sheet.PageSetup.EvenHeaderString = "&\"Arial\"&12&B&KFF0000Even_Header";
sheet.PageSetup.EvenFooterString = "&\"Arial\"&12&B&KFF0000Even_Footer";

wb.SaveToFile("OddEvenHeaderFooter.xlsx", ExcelVersion.Version2013);
[VB.NET]
Dim wb As New Workbook()
Dim sheet As Worksheet = wb.Worksheets(0)

sheet.Range("A1").Text = "Page 1"
sheet.Range("J1").Text = "Page 2"

sheet.PageSetup.DifferentOddEven = 1
sheet.PageSetup.OddHeaderString = "&""Arial""&12&B&KFFC000Odd_Header"
sheet.PageSetup.OddFooterString = "&""Arial""&12&B&KFFC000Odd_Footer"
sheet.PageSetup.EvenHeaderString = "&""Arial""&12&B&KFF0000Even_Header"
sheet.PageSetup.EvenFooterString = "&""Arial""&12&B&KFF0000Even_Footer"

wb.SaveToFile("OddEvenHeaderFooter.xlsx", ExcelVersion.Version2013)