DEV Community

jelizaveta
jelizaveta

Posted on

Automating Excel Printing in C#: From Page Setup to Silent Print

Automating Excel Printing in C#: From Page Setup to Silent Print

In office automation development, Excel document printing is a common yet relatively complex requirement. This article provides a detailed guide on how to use Spire.XLS for .NET to configure Excel print settings and implement silent printing in C#.

Introduction to Spire.XLS

Spire.XLS is a professional .NET Excel component that allows you to create, read, modify, and print Excel documents in C# without installing Microsoft Office. It offers a rich set of APIs and supports Excel formats from Excel 97–2003 to the latest versions.

Installation Methods

You can install Spire.XLS via NuGet.

Method 1: Using NuGet Package Manager Console

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

Method 2: Using Visual Studio NuGet Manager UI

  1. Right-click your project → Manage NuGet Packages
  2. Search for Spire.XLS
  3. Click Install

Detailed Excel Print Page Setup

Before printing an Excel file, proper page setup is crucial. The following example demonstrates how to comprehensively configure print settings for a worksheet:

using Spire.Xls;
namespace ExcelPrintSetup
{
    class Program
    {
        static void Main(string[] args)
        {
            // Create a Workbook object and load the Excel document
            Workbook workbook = new Workbook();
            workbook.LoadFromFile("Test.xlsx");

            // Get the PageSetup object of the first worksheet
            Worksheet worksheet = workbook.Worksheets[0];
            PageSetup pageSetup = worksheet.PageSetup;

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

            // Specify print area and title rows
            pageSetup.PrintArea = "A1:F7";        // Print only A1 to F7
            pageSetup.PrintTitleRows = "$1:$2";   // Repeat first two rows on every page

            // Set print options
            pageSetup.IsPrintHeadings = true;     
            pageSetup.IsPrintGridlines = true;    
            pageSetup.PrintComments = PrintCommentType.InPlace;

            // Set print quality and other options
            pageSetup.PrintQuality = 300;         
            pageSetup.BlackAndWhite = true;       
            pageSetup.Order = OrderType.OverThenDown;  
            pageSetup.IsFitToPage = true;         

            // Save the document with updated settings
            workbook.SaveToFile("PagePrintOptions.xlsx", ExcelVersion.Version2016);

            Console.WriteLine("Print settings saved successfully!");
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Implementing Silent Printing

In real-world applications, silent (background) printing without user interaction is often required. The following example demonstrates how to specify a printer and perform silent printing:

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

namespace ExcelSilentPrint
{
    class Program
    {
        static void Main(string[] args)
        {
            // Create Workbook and load document
            Workbook workbook = new Workbook();
            workbook.LoadFromFile("Test.xlsx");

            // Fit worksheet to one page
            PageSetup pageSetup = workbook.Worksheets[0].PageSetup;
            pageSetup.IsFitToPage = true;

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

            // Configure printer settings
            PrinterSettings settings = workbook.PrintDocument.PrinterSettings;
            settings.PrinterName = "HP LaserJet P1007";
            settings.Duplex = Duplex.Simplex;
            settings.FromPage = 1;
            settings.ToPage = 3;

            // Execute printing
            workbook.PrintDocument.Print();

            Console.WriteLine("Print job sent to printer!");
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Core Features Explained

1. Key Page Setup Features

Feature Property/Method Description
Margins TopMargin, BottomMargin, etc. Precisely control page layout
Print Area PrintArea Print specific cell ranges only
Title Rows PrintTitleRows Repeat headers on each page
Gridlines IsPrintGridlines Control gridline printing
Fit to Page IsFitToPage Prevent content from being cut off

2. Advantages of Silent Printing

  • Hidden printing process : Use StandardPrintController to suppress the print dialog
  • Precise control : Specify printer, page range, and duplex mode
  • Batch processing : Ideal for automated multi-document printing scenarios

Advanced Features

Retrieve Installed Printers

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

Set Paper Size and Orientation

pageSetup.PaperSize = PaperSizeType.A4;
pageSetup.Orientation = PageOrientationType.Landscape;
Enter fullscreen mode Exit fullscreen mode

Practical Application Scenarios

  1. Automated Report Printing – Scheduled tasks that automatically print reports
  2. Batch Document Processing – Printing multiple Excel files in bulk
  3. Custom Print Formats – Preset different layouts for different reports
  4. Network Printing Management – Print to network printers by specifying printer name

Important Notes

  1. Printer Name – Ensure the specified printer exists on the system
  2. Exception Handling – Use try-catch blocks to handle printing errors
  3. Permission Check – Ensure the application has printer access permissions
  4. Resource Release – Dispose of the Workbook object after printing

Conclusion

With the Spire.XLS library, implementing automated Excel printing in C# becomes straightforward and efficient. Whether configuring simple page settings or handling complex batch print tasks, Spire.XLS provides a comprehensive solution.

By applying the code examples in this article, you can quickly integrate Excel printing functionality into your C# projects.

Remember, well-configured print settings not only improve document professionalism but also help save paper and ink—contributing to a greener office environment.

Top comments (0)