Use the Excel Export API to Specify Print Settings

  • 3 minutes to read

The examples below demonstrate how to fine-tune print settings to create the required layout of a printed page.

Print Options

To specify printing options for a worksheet, set the IXlSheet.PrintOptions property to an instance of the XlPrintOptions class. Using the XlPrintOptions object’s properties, you can print gridlines (XlPrintOptions.GridLines), add column headings to the top of the printout and row headings to the left side of the printout (XlPrintOptions.Headings), and center data on the printed page (XlPrintOptions.HorizontalCentered and XlPrintOptions.VerticalCentered).

The example below demonstrates how to specify print settings for a worksheet.

// Specify print options for the worksheet.
sheet.PrintOptions = new XlPrintOptions();
// Print row and column headings.
sheet.PrintOptions.Headings = true;
// Print gridlines.
sheet.PrintOptions.GridLines = true;
// Center worksheet data on a printed page.
sheet.PrintOptions.HorizontalCentered = true;
sheet.PrintOptions.VerticalCentered = true;

Page Setup

To define page formatting options, set the IXlSheet.PageSetup property to an instance of the XlPageSetup class. The XlPageSetup object enables you to specify page orientation (XlPageSetup.PageOrientation), paper size (XlPageSetup.PaperKind), page order (XlPageSetup.PagePrintOrder), print quality (XlPageSetup.HorizontalDpi and XlPageSetup.VerticalDpi), number of copies (XlPageSetup.Copies) and other printing options.

To fit worksheet content into a specific number of pages, set the XlPageSetup.FitToPage property to true and specify the desired number of horizontal pages (XlPageSetup.FitToWidth) and vertical pages (XlPageSetup.FitToHeight) on which the worksheet should be printed. You can also scale the worksheet content arbitrarily by specifying the scale percentage using the XlPageSetup.Scale property. Note that this property takes effect only when the XlPageSetup.FitToPage property is false.

// Specify page settings for the worksheet.
sheet.PageSetup = new XlPageSetup();
// Select the paper size.
sheet.PageSetup.PaperKind = System.Drawing.Printing.PaperKind.A4;
// Set the page orientation to Landscape.
sheet.PageSetup.PageOrientation = XlPageOrientation.Landscape;
//  Scale the print area to fit to one page wide.
sheet.PageSetup.FitToPage = true;
sheet.PageSetup.FitToWidth = 1;
sheet.PageSetup.FitToHeight = 0;
//  Print in black and white.
sheet.PageSetup.BlackAndWhite = true;
// Specify the number of copies.
sheet.PageSetup.Copies = 2;

See Also

See the following examples to learn more about how to specify other printout options using the Excel Export API.