DEV Community

jelizaveta
jelizaveta

Posted on

Print Excel Documents Using C# (Detailed Tutorial)

Implementing high-quality Excel printing in a .NET environment is not easy. Developers need to precisely control settings such as page margins, paper size, gridline display, and more—while also supporting both physical printers and virtual PDF printers. Without a mature solution, these requirements often consume a lot of time for tuning and adaptation.

This article guides you through building a complete Excel printing solution using Spire.XLS for .NET together with the System.Drawing.Printing namespace. By following this tutorial, you will learn core skills including loading an Excel document, configuring print parameters, printing to a physical printer, and converting Excel to PDF, etc.

1. Preparation

1.1 Environment Requirements

  • .NET Framework 4.0 or later , or .NET Core/.NET 5+
  • Visual Studio 2017 or later

1.2 Install Spire.XLS for .NET

Install via the NuGet package manager:

Install-Package Spire.XLS
Enter fullscreen mode Exit fullscreen mode

Or install in Visual Studio by searching for Spire.XLS through the NuGet package manager.

2. Import the Core Namespaces

using Spire.Xls;
using System.Drawing.Printing;
Enter fullscreen mode Exit fullscreen mode

3. Printing to a Physical Printer

3.1 Complete Code Example

using Spire.Xls;
using System.Drawing.Printing;

namespace PrintExcel
{
    class Program
    {
        static void Main(string[] args)
        {
            // 1. Load the Excel document
            Workbook workbook = new Workbook();
            workbook.LoadFromFile("Input.xlsx");

            // 2. Iterate through and configure each worksheet
            for (int i = 0; i < workbook.Worksheets.Count; i++)
            {
                Worksheet worksheet = workbook.Worksheets[i];
                PageSetup pageSetup = worksheet.PageSetup;

                // Set margins (unit: inches)
                pageSetup.TopMargin = 0.3;
                pageSetup.BottomMargin = 0.3;
                pageSetup.LeftMargin = 0.3;
                pageSetup.RightMargin = 0.3;

                // Print gridlines
                pageSetup.IsPrintGridlines = true;

                // Fit all columns to one page wide
                pageSetup.FitToPagesWide = 1;
                pageSetup.FitToPagesTall = 0;

                // Set paper size to A4
                pageSetup.PaperSize = PaperSizeType.PaperA4;
            }

            // 3. Get printer settings
            PrinterSettings settings = workbook.PrintDocument.PrinterSettings;

            // 4. Specify printer name
            settings.PrinterName = "Your Printer Name";

            // 5. Execute printing
            workbook.PrintDocument.Print();
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

3.2 Code Explanation

Loading the Excel Document

Workbook workbook = new Workbook();
workbook.LoadFromFile("Input.xlsx");
Enter fullscreen mode Exit fullscreen mode

Create a Workbook object and load the Excel file to be printed using LoadFromFile.

Page Setup (PageSetup)

Loop through each worksheet and apply detailed page configuration:

  • Page margins : TopMargin, BottomMargin, LeftMargin, RightMargin set margins on all sides (unit: inches).
  • Gridlines : IsPrintGridlines = true keeps gridlines in the printout, making the data easier to read.
  • Scaling settings :
    • FitToPagesWide = 1: scale all columns to fit on one page width
    • FitToPagesTall = 0: do not limit row count; paginate based on actual height
  • Paper size : PaperSize = PaperSizeType.PaperA4 sets the paper to A4.

Printer Configuration and Execution

PrinterSettings settings = workbook.PrintDocument.PrinterSettings;
settings.PrinterName = "Your Printer Name";
workbook.PrintDocument.Print();
Enter fullscreen mode Exit fullscreen mode

Get the printer settings object, set the target printer name, then call Print() to start printing.

4. Printing to a Virtual Printer (Microsoft Print to PDF)

4.1 Complete Code Example

using Spire.Xls;
using System.Drawing.Printing;

namespace PrintExcel
{
    class Program
    {
        static void Main(string[] args)
        {
            // Load the Excel document
            Workbook workbook = new Workbook();
            workbook.LoadFromFile("Input.xlsx");

            // Configure worksheets (same as previous example)
            for (int i = 0; i < workbook.Worksheets.Count; i++)
            {
                Worksheet worksheet = workbook.Worksheets[i];
                PageSetup pageSetup = worksheet.PageSetup;
                pageSetup.TopMargin = 0.3;
                pageSetup.BottomMargin = 0.3;
                pageSetup.LeftMargin = 0.3;
                pageSetup.RightMargin = 0.3;
                pageSetup.IsPrintGridlines = true;
                pageSetup.FitToPagesWide = 1;
                pageSetup.FitToPagesTall = 0;
                pageSetup.PaperSize = PaperSizeType.PaperA4;
            }

            // Set the virtual printer
            PrinterSettings settings = workbook.PrintDocument.PrinterSettings;
            settings.PrintToFile = true;  // Enable printing to a file
            settings.PrinterName = "Microsoft Print to PDF";  // Specify virtual printer

            // Execute printing and specify the output PDF path
            workbook.PrintDocument.Print("ToPdf.pdf");
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

4.2 Key Points

The main differences from printing to a physical printer:

Setting Description
settings.PrintToFile = true Enable “print to file” mode
settings.PrinterName = "Microsoft Print to PDF" Specify the virtual printer name
workbook.PrintDocument.Print("ToPdf.pdf") Use thePrintmethod with a parameter to set the output file path

5. Common Printer Name Reference

Default Printer on Windows

// Get default printer name
string defaultPrinter = new PrinterSettings().PrinterName;
Enter fullscreen mode Exit fullscreen mode

Common Printer Names

Printer Type Example Name
Microsoft Print to PDF "Microsoft Print to PDF"
Microsoft XPS Document Writer "Microsoft XPS Document Writer"
Foxit Reader PDF Printer "Foxit Reader PDF Printer"
Physical printer e.g.,"HP LaserJet MFP M227fdw"

Get All Installed Printers

foreach (string printer in PrinterSettings.InstalledPrinters)
{
    Console.WriteLine(printer);
}
Enter fullscreen mode Exit fullscreen mode

6. More Page Setup Options

6.1 Common PageSetup Properties

// Set print orientation
pageSetup.Orientation = PageOrientationType.Landscape;  // Landscape
pageSetup.Orientation = PageOrientationType.Portrait;   // Portrait

// Set zoom level (1-100)
pageSetup.Zoom = 90;

// Set header/footer margins
pageSetup.HeaderMargin = 0.5;
pageSetup.FooterMargin = 0.5;

// Set print area
pageSetup.PrintArea = "A1:F50";

// Set title rows (repeat print on every page)
pageSetup.PrintTitleRows = "$1:$2";

// Center horizontally/vertically
pageSetup.HorzAlignment = PageSetupHorzAlignment.Center;
pageSetup.VertAlignment = PageSetupVertAlignment.Center;
Enter fullscreen mode Exit fullscreen mode

6.2 Paper Size Types

pageSetup.PaperSize = PaperSizeType.PaperA3;
pageSetup.PaperSize = PaperSizeType.PaperA4;
pageSetup.PaperSize = PaperSizeType.PaperA5;
pageSetup.PaperSize = PaperSizeType.PaperLetter;
pageSetup.PaperSize = PaperSizeType.PaperLegal;
Enter fullscreen mode Exit fullscreen mode

7. Advanced Scenario: Silent Printing

If you need to implement printing without dialogs:

// Hide print dialog
workbook.PrintDocument.PrintController = new StandardPrintController();

// Set number of copies
workbook.PrintDocument.PrinterSettings.Copies = 2;

// Execute printing silently
workbook.PrintDocument.Print();
Enter fullscreen mode Exit fullscreen mode

8. Exception Handling

It’s recommended to add exception handling in real applications:

try
{
    // Check whether the printer exists
    if (!PrinterSettings.InstalledPrinters.Cast<string>().Any(p => p == printerName))
    {
        throw new Exception($"Printer '{printerName}' does not exist");
    }

    workbook.PrintDocument.Print();
    Console.WriteLine("Print successful!");
}
catch (Exception ex)
{
    Console.WriteLine($"Print failed: {ex.Message}");
}
Enter fullscreen mode Exit fullscreen mode

9. Summary

This article provides a complete solution for printing Excel documents using C# and the Spire.XLS library:

Scenario Key Code
Physical printer SetPrinterName+ callPrint()
PDF output SetPrintToFile = true+ callPrint("output.pdf")
Page configuration Use thePageSetupobject to set margins, paper, scaling, etc.
Silent printing SetPrintController = new StandardPrintController()

Spire.XLS offers many page setup options, and combined with the printer management capabilities of System.Drawing.Printing, it can flexibly meet various Excel printing requirements. Whether you’re batch-printing reports or converting Excel to PDF for archiving, the code in this article can serve as a reliable foundation.

Top comments (0)