Add header and footer in Excel

  • NPOI
  • Spire.XLS
  • Download Sample Code

using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace NPOI
{
    class Program
    {
        static void Main(string[] args)
        {
            //Load workbook
            IWorkbook workbook = new XSSFWorkbook(new FileStream("../../../Data/Sample.xlsx", FileMode.Open));

            //Get the first worksheet
            ISheet sheet = workbook.GetSheetAt(0);

            //Set header
            IHeader header = sheet.Header;
            header.Right = "Header";

            //Set footer
            IFooter footer = sheet.Footer;
            footer.Center = "Footer";
           
            //Save the file
            FileStream file = File.Create("HeaderFooter.xlsx");
            workbook.Write(file);
            file.Close();

            //Launch the file
            System.Diagnostics.Process.Start("HeaderFooter.xlsx");
        }
    }
}


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Spire.Xls;

namespace Spire.XLS
{
    class Program
    {
        static void Main(string[] args)
        {
            //Load workbook         
            Workbook workbook = new Workbook();
            workbook.LoadFromFile("../../../Data/Sample.xlsx");

            //Gets the first worksheet
            Worksheet mysht = workbook.Worksheets[0];

            //Set header
            mysht.PageSetup.RightHeader = "Header";

            //Set footer
            mysht.PageSetup.CenterFooter = "Footer";

            //Save and Launch
            workbook.SaveToFile("HeaderFooter.xlsx", ExcelVersion.Version2013);
            System.Diagnostics.Process.Start("HeaderFooter.xlsx");

        }
    }
}