DEV Community

Cover image for Create Print-Ready Excel Reports in C# with Programmatic Page Setup
Zahra Sandra Nasaka for Syncfusion, Inc.

Posted on • Originally published at syncfusion.com on

Create Print-Ready Excel Reports in C# with Programmatic Page Setup

TL;DR: Repetitive Excel page setup wastes hours and increases the risk of formatting errors. This guide demonstrates how to manage print settings in C#, from margins and headers to scaling, ensuring your reports remain consistent and ready for printing.

Preparing Excel files for printing shouldn’t feel like a chore. Instead of tweaking settings manually, configure them programmatically in C# to achieve optimal results. This approach ensures consistent, error-free formatting for reports, invoices, and dashboards fast.

To simplify this process, the Syncfusion® .NET Excel Library (Essential XlsIO) offers a powerful API that enables you to create, read, and edit Excel files in C# without relying on Microsoft Office. With Essential XlsIO, you can programmatically control page settings, such as orientation, scaling, margins, headers/footers, print area, and more, all directly from your C# code.

In this guide, you’ll learn how to configure key page setup options programmatically, including:

Let’s dive in and explore how to set up these essential page settings in Excel using C#.

Prerequisites

Before you start, ensure you have:

Setting up your .NET project

  1. Create a new .NET Core console application in Visual Studio.
  2. Install the Syncfusion.XlsIO.Net.Core NuGet package.

Applying page setup options in Excel using C

In this example, we will generate a monthly sales report in an Excel document and apply professional page setup options to make it print-ready.

Step 1: Generate monthly sales report data

Start by creating an Excel document using Essential XlsIO.

using (ExcelEngine engine = new ExcelEngine())
{
    IApplication app = engine.Excel;
    app.DefaultVersion = ExcelVersion.Xlsx;

    IWorkbook workbook = app.Workbooks.Create(1);
    IWorksheet worksheet = workbook.Worksheets[0];
    worksheet.Name = "Monthly Sales";

    // Title
    worksheet.Range["A1"].Text = "Monthly Sales Report";
    worksheet.Range["A1"].CellStyle.Font.Bold = true;
    worksheet.Range["A1"].CellStyle.Font.Size = 16;

    // Headers
    worksheet.Range["A3"].Text = "Order ID";
    worksheet.Range["B3"].Text = "Date";
    worksheet.Range["C3"].Text = "Region";
    worksheet.Range["D3"].Text = "Salesperson";
    worksheet.Range["E3"].Text = "Units";
    worksheet.Range["F3"].Text = "Amount";
    worksheet.Range["A3:F3"].CellStyle.Font.Bold = true;
    worksheet.Range["A3:F3"].CellStyle.Color = Syncfusion.Drawing.Color.FromArgb(240, 240, 240);

    // Generate Sales Data
    int row = 4;
    string[] regions = new[] { "North", "South", "West", "East" };
    Random rnd = new Random(17);
    DateTime month = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1);

    foreach (string region in regions)
    {
        worksheet.Range["A" + row].Text = region + " Region";
        worksheet.Range["A" + row].CellStyle.Font.Bold = true;
        worksheet.Range["A" + row].CellStyle.Font.Size = 12;
        row++;

        for (int count = 0; count < 20; count++)
        {
            worksheet.Range["A" + row].Text = $"ORD-{region.Substring(0, 1)}-{1000 + count}";
            worksheet.Range["B" + row].DateTime = month.AddDays(rnd.Next(0, 28));
            worksheet.Range["B" + row].NumberFormat = "dd-MMM";
            worksheet.Range["C" + row].Text = region;
            worksheet.Range["D" + row].Text = "Rep " + rnd.Next(1, 6);
            worksheet.Range["E" + row].Number = rnd.Next(1, 25);
            worksheet.Range["F" + row].Number = Math.Round(2500 + rnd.NextDouble() * 20000, 2);
            worksheet.Range["F" + row].NumberFormat = "#,##0.00";
            row++;
        }
        row++;
    }
}
Enter fullscreen mode Exit fullscreen mode

Step 2: Apply page setup options

Now that the data is ready, let’s configure the worksheet’s page setup options for professional printing.

Orientation

Page orientation determines whether your worksheet prints in Portrait (vertical) or Landscape (horizontal). For wider datasets, Landscape is ideal.

Here, we will set the page orientation to Landscape.

IPageSetup pageSetup = worksheet.PageSetup;

// Set Orientation to Landscape
pageSetup.Orientation = ExcelPageOrientation.Landscape;
Enter fullscreen mode Exit fullscreen mode

Paper size

Paper size specifies the physical dimensions of your printed page. Common options include A4, Letter, and Legal. Choosing the right size ensures your report looks consistent across all regions. For instance, A4 is the standard in most countries, while Letter is the typical size in the United States.

Let’s set the paper size to A4, as shown in the following code example.

IPageSetup pageSetup = worksheet.PageSetup;

// Set Paper Size to A4
pageSetup.PaperSize = ExcelPaperSize.PaperA4;
Enter fullscreen mode Exit fullscreen mode

Margin

Margins are the blank spaces around the edges of your worksheet. Proper margins prevent content from being cut off and improve readability. Use smaller margins to fit more data or wider margins for binding and notes.

Let’s configure margins in inches as shown in the following code example.

IPageSetup pageSetup = worksheet.PageSetup;

// Set Margins in inches

// Top, Bottom - 0.5 inch
pageSetup.TopMargin = 0.5;
pageSetup.BottomMargin = 0.5;

// Left, Right - 0.25 inch
pageSetup.LeftMargin = 0.25;
pageSetup.RightMargin = 0.25;

// Header, Footer - 0.3 inch
pageSetup.HeaderMargin = 0.3;
pageSetup.FooterMargin = 0.3;
Enter fullscreen mode Exit fullscreen mode

Print titles

When your worksheet spans multiple pages, repeating header rows and columns on every page makes the printed report easier to read. Without this feature, readers may lose context when navigating later pages.

For example:

  • Repeat the header row containing column names, such as Region, Sales Person, and Units.

Refer to the following code example.

IPageSetup pageSetup = worksheet.PageSetup;

// Repeat the 3rd row on every printed page
pageSetup.PrintTitleRows = "$3:$3";

// Repeat the first column on every printed page
pageSetup.PrintTitleColumns = "$A:$A";
Enter fullscreen mode Exit fullscreen mode

By setting these options, your headers remain visible across all pages, improving readability and maintaining context for longer reports.

Print area

By default, Excel prints the entire worksheet, which often includes helper columns, notes, or hidden calculations you don’t want in the final report. The Print Area feature allows you to define a specific range of cells for printing, ensuring that only relevant data appears.

Why is this important?

  • Cleaner reports: Exclude unnecessary rows or columns.
  • Better control: Print only the main dataset, not formulas or hidden sections.
  • Dynamic flexibility: Adjust the range based on your data size.

For example, if your report starts at row 3 and ends at the last used row in column F, you can set the print area like this.

IPageSetup pageSetup = worksheet.PageSetup;

// Define the print area from A3 to the last used row in column F
int lastRow = worksheet.UsedRange.LastRow;
pageSetup.PrintArea = $"A3:F{lastRow}"
Enter fullscreen mode Exit fullscreen mode

Header and footer

Headers and footers add valuable context to printed pages, such as page numbers, dates, file names, or branding. This makes reports easier to read and share. Dynamic fields like &P (current page), &N (total pages), &D ] (date), and &T (time) keep content updated automatically. You can also format text (font, size, style) and include elements like your company name or logo for a professional finish.

The following are the commonly used tokens for setting header and footer content in an Excel document using XlsIO.

Token Meaning
&P Current page number
&N Total number of pages
&D Current date
&T Current time
&A Sheet name
&F File name
&Z File path
&G Picture placeholder
&B Bold toggle
&I Italic toggle
&U Single underline toggle
&E Double underline toggle
&nn Font size (pt)
&"Font,Style" Font family and style
&Krrrrggggbbbb Font color (hex)
\n Line break
&& Literal ampersand

Here’s how to apply headers and footers in C#.

IPageSetup pageSetup = worksheet.PageSetup;

// Apply left header as "Monthly Sales" with Calibri font of size 14 and bold
pageSetup.LeftHeader = "&\"Calibri,Bold\"&14 Monthly Sales";

// Apply center header as "Month Year" with bold
pageSetup.CenterHeader = "&B&10" + month.ToString("MMMM yyyy");

// Apply right header with page number and total pages
pageSetup.RightHeader = "Page &P of &N";

// Apply left footer with sheet name
pageSetup.LeftFooter = "Sheet: &A";

// Apply center footer with current date and time
pageSetup.CenterFooter = "Generated: &D &T";

// Apply right footer with file name
pageSetup.RightFooter = "&F";
Enter fullscreen mode Exit fullscreen mode

Page breaks

Page breaks give you precise control over where a new page begins when printing your Excel worksheets. This is especially useful for large reports or grouped data, as it ensures each section starts on a fresh page for improved readability. For example, in a sales report, each region can begin on a new page for easier navigation.

You can programmatically add:

  • Horizontal page breaks (before a specific row)
  • Vertical page breaks (before a specific column)

Here’s how to add horizontal page breaks dynamically based on data blocks.

IPageSetup pageSetup = worksheet.PageSetup;

// Add a page break before each region. Assuming each region block (title + data) takes 22 rows including spacing.
int firstRegionRow = 4;
int blockHeight = 22;
for (int count = 1; count < regions.Length; count++)
{
    int titleRow = firstRegionRow + count * blockHeight;

    // Add a horizontal page break before the title row of each region
    worksheet.HPageBreaks.Add(worksheet.Range["A" + titleRow]);
}
Enter fullscreen mode Exit fullscreen mode

Similarly, you can add vertical page breaks using IWorksheet.VPageBreaks in the .NET Excel library.

Scaling

Scaling controls how your worksheet fits onto printed pages. Use FitToPagesWide and FitToPagesTall to control the number of pages your worksheet spans when printed, and use Zoom for fixed percentage scaling.

  • FitToPagesWide = 1 and FitToPagesTall = 0: Ideal for wide reports (e.g., Monthly Sales Report), so content fits on one page horizontally while flowing vertically.
  • FitToPagesWide = 1 and FitToPagesTall = 1: Forces the entire worksheet onto a single page.
  • Zoom: Use a fixed percentage only when Fit settings are not applied. Excel ignores Zoom if FitToPagesWide or FitToPagesTall is set.

Here is how to apply both Zoom and Fit-to-Page settings.

IPageSetup pageSetup = worksheet.PageSetup;

// Set the scaling to 120%. Not applied due to fit settings.
pageSetup.Zoom = 120;

// Fit to 1 page wide and unlimited tall
pageSetup.FitToPagesTall = 0;

// Fit to 1 page wide
pageSetup.FitToPagesWide = 1;
Enter fullscreen mode Exit fullscreen mode

Additional options

Apart from major page setup options, you can fine-tune the print layout for a polished look. The options include:

  • Hiding gridlines for a cleaner appearance.
  • Suppressing row and column headings for a professional finish.
  • Controlling comments display, enabling black-and-white or draft mode, and adjusting page numbering to match your branding or printing needs.

Let’s apply these final tweaks to make the print view look its best.

IPageSetup pageSetup = worksheet.PageSetup;

// Set gridlines to be hidden in the printed page
pageSetup.PrintGridlines = false;

// Set center the sheet horizontally on the page
pageSetup.CenterHorizontally = true;

// Set not to center the sheet vertically on the page
pageSetup.CenterVertically = false;

//Do not print headings
pageSetup.PrintHeadings = false;

// Do not print comments
pageSetup.PrintComments = ExcelPrintLocation.PrintNoComments;

// Do not print in black and white only
pageSetup.BlackAndWhite = true;

// Draft quality set to false
pageSetup.Draft = false;

// Set first page number as 2
pageSetup.FirstPageNumber = 2; 
Enter fullscreen mode Exit fullscreen mode

We have now successfully applied the page setup options to the Excel document. When the user initiates printing, these settings are automatically detected by the printer, ensuring a properly formatted monthly sales report.

Applying page settings to the Excel document using C#


Applying page settings to the Excel document using C#

Use cases

Page setup options are essential for producing professional, print-ready reports. Here are some practical scenarios:

  • Wide reports, such as sales summaries or dashboards, benefit from Landscape mode.
  • International reports require A4 paper, while U.S. clients expect Letter-Sized Paper.
  • Financial statements require wider margins for binding; dashboards, on the other hand, need tighter margins for maximum data visibility.
  • Inventory reports with hundreds of rows remain readable when column titles are repeated.
  • Client invoices exclude hidden calculations and notes by setting a print area.
  • Audit reports include page numbers and timestamps for compliance.

GitHub reference

Also, refer to the page setup options in Excel using C# demo on the GitHub repository.

Conclusion

Thanks for reading! In this blog, we have learned how to programmatically apply page setup options in an Excel document using C#. By implementing these techniques, you can transform repetitive formatting tasks into a one-time solution that saves hours and ensures professional, print-ready reports.

If you’re already a Syncfusion user, download the setup from the license and downloads page. Otherwise, start with a free 30-day trial and experience the benefits firsthand.

Need help or have questions? Reach out through our support forum, support portal, or feedback portal. We’re always happy to assist you!

Related blogs

This article was originally published at Syncfusion.com.

Top comments (0)