Page orientation Excel Addin C#

Page orientation Excel Addin C#

Page Orientation:

By default, Microsoft Excel prints worksheets in portrait orientation (taller than wide). You can change the page orientation to landscape to print it sideways.

Change the page orientation in the worksheet

  • Select the worksheet or worksheets for which you want to change the orientation. How to select worksheets. …
  • On the Page Layout tab, in the Page Setup group, click Orientation, and then click Portrait or Landscape.

Let’s do some coding to toggle page orientation, the code will check if page is portrait then it will toggle landscape property to make page landscape and vise versa.

Prerequisites:

  • Visual Studio 2015 or above having Microsoft Office for Developer Tool installed
  • Create Excel Addin in C# code style (Visual Studio Tools for Office)
  • Create a ribbon designer and put button

Code example:

private void btnPageOrientation_Click(object sender, RibbonControlEventArgs e)
{
	//reference active sheet
	excel.Worksheet oWorksheet = Globals.ThisAddIn.Application.ActiveSheet;

	//get Page Setup object reference
	excel.PageSetup oPageSetup = oWorksheet.PageSetup;

	//toggle page orientation
	if (oPageSetup.Orientation == excel.XlPageOrientation.xlLandscape)
		oPageSetup.Orientation = excel.XlPageOrientation.xlPortrait;
	else
		oPageSetup.Orientation = excel.XlPageOrientation.xlLandscape;
}

Next : Change paper size in Excel Addin

Leave a Reply

Your email address will not be published.