How to set Excel page margins before printing a worksheet in C#

Page margins in Excel are the blank spaces between the worksheet data and the edges of the printed page. It is where we could add headers, footers and page numbers, etc. Before printing a worksheet, it's necessary to specify custom margins for a better layout. In Excel, we could set top margin, bottom margin, left margin, right margin, header margin, and footer margin, which are all supported by Spire.XLS library. This article is going to introduce the method to set Excel page margins in C# using Spire.XLS.

Note: Before start, please download the latest version of Spire.Doc and add the .dll in the bin folder as the reference of Visual Studio.

Step 1: Initial a new workbook and load the sample document.

            Workbook workbook = new Workbook();
            workbook.LoadFromFile("Sample.xlsx");
            Worksheet sheet = workbook.Worksheets[0];

Step 2: Set margins for top, bottom, left and right of the worksheet page. Here the unit of measure is Inch (1 inch=2.54 cm).

            sheet.PageSetup.TopMargin = 0.3;
            sheet.PageSetup.BottomMargin = 1;
            sheet.PageSetup.LeftMargin = 0.2;
            sheet.PageSetup.RightMargin = 1;

Step 3: Set the header margin and footer margin.

            sheet.PageSetup.HeaderMarginInch = 0.1;
            sheet.PageSetup.FooterMarginInch = 0.5;

Step 4: Save the document and launch to see effect.

            workbook.SaveToFile("S3.xlsx", ExcelVersion.Version2010);
            System.Diagnostics.Process.Start("S3.xlsx");

Effect:

How to set Excel page margins before printing a worksheet in C#

Full codes:

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

namespace How_to_set_Excel_margin_to_print
{
    class Program
    {
        static void Main(string[] args)
        {
            Workbook workbook = new Workbook();
            workbook.LoadFromFile("Sample.xlsx");
            Worksheet sheet = workbook.Worksheets[0];

            sheet.PageSetup.TopMargin = 0.3;
            sheet.PageSetup.BottomMargin = 1;
            sheet.PageSetup.LeftMargin = 0.2;
            sheet.PageSetup.RightMargin = 1;

            sheet.PageSetup.HeaderMarginInch = 0.1;
            sheet.PageSetup.FooterMarginInch = 0.5;

            workbook.SaveToFile("S3.xlsx", ExcelVersion.Version2010);
            System.Diagnostics.Process.Start("S3.xlsx");

        }
    }
}