Insert Image and Formatted Text in Excel Header or Footer in C#

Excel header or footer, which presents information like page numbers, the creation date, the logo of your company, and even customized text, can be of use in printed worksheets. In this article, you’ll learn how to insert images and formatted text in Excel header or footer in C#.

This solution relies on Spire.XLS, an Excel processing library, which provides a PageSetup class to deal with all page setup settings. Specifically, it contains LeftHeader, CenterHeader, LeftHeaderImage, OddHeaderStringand similar properties that represent header/footer text, image, odd header/footer and even header/footer in Excel. Besides, this component provides some special script commands, which are used to get the dynamic value like page number or format the header or footer text.

Script D
&P The current page number
&N The total number of pages
&D The current data
&T The current time
&G A picture
&A The worksheet name
&F The file name
&B Make text bold
&I Italicize text
&U Underline text
&”font name” Represents a font name, for example, &”Aril”
&font size Represents font size, for example, &12
&K Represents font color, for example, &KFF0000

Insert Image to Header

  //create a word document
Workbook wb = new Workbook();

//get the first worksheet
Worksheet sheet = wb.Worksheets[0];

//load a pic to Image object
Image image = Image.FromFile("company-logo.jpg");

//scale the image
Bitmap bitmap = new Bitmap(image, new Size(image.Width / 4, image.Height / 4));

//insert image to left header
sheet.PageSetup.LeftHeaderImage = bitmap;
sheet.PageSetup.LeftHeader = "&G";

//save the file
wb.SaveToFile("Insert_Text_Footer.xlsx", ExcelVersion.Version2013);


Insert Formatted Text to Footer

 //create an object of Workbook class   
Workbook wb = new Workbook();

//get the first sheet  
Worksheet sheet = wb.Worksheets[0];

//format a string with script commands and assign it to CenterFooter   
sheet.PageSetup.CenterFooter = "&\"Arial\"&B&12&KFF0000Copyright © 2017 JMD. All Rights Reserved.";

//save the file
wb.SaveToFile("Insert_Text_Footer.xlsx", ExcelVersion.Version2013);



Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s