How to Print Excel Files in C#, VB.NET

Spire.XLS is a professional .NET Excel component which provides efficient way to create, manage and manipulate Excel spreadsheet from .NET application without the need for Microsoft Excel on either the develop or client machines.

After we finish editing Excel spreadsheet, we will probably need to print the sheet. At this time, we can also use Spire.XLS to print the entire Excel file or selected pages with default and advanced print options. For instance, we’re allowed to print to default printer or any other network connected printer.

Print Dialog Box:

How to Print Excel Files in C#, VB.NET

C# code snippet of print Excel file:

Step 1: Create a new instance of workbook class and load the sample file.

Workbook workbook = new Workbook();
workbook.LoadFromFile("d:\\sample.xlsx")

Step 2: Create a new instance of System.Window.Forms.PrintDialog class.

PrintDialog dialog = new PrintDialog();

Step 3: Set parameter values of the dialog.

dialog.AllowPrintToFile = true;
dialog.AllowCurrentPage = true;
dialog.AllowSomePages = true;
dialog.AllowSelection = true;
dialog.UseEXDialog = true;

Step 4: Set print pages and choose simplex printing mode.

dialog.PrinterSettings.Duplex = Duplex.Simplex;
dialog.PrinterSettings.FromPage = 0;
dialog.PrinterSettings.ToPage = 8;
dialog.PrinterSettings.PrintRange = PrintRange.SomePages;

Step 5: Get the print document and print.

workbook.PrintDialog = dialog;
PrintDocument pd = workbook.PrintDocument;
if (dialog.ShowDialog() == DialogResult.OK)
{ pd.Print(); }

Full code:

[C#]
Workbook workbook = new Workbook();
workbook.LoadFromFile(InputFile);
PrintDialog dialog = new PrintDialog();
dialog.AllowPrintToFile = true;
dialog.AllowCurrentPage = true;
dialog.AllowSomePages = true;
dialog.AllowSelection = true;
dialog.UseEXDialog = true;
dialog.PrinterSettings.Duplex = Duplex.Simplex;
dialog.PrinterSettings.FromPage = 0;
dialog.PrinterSettings.ToPage = 8;
dialog.PrinterSettings.PrintRange = PrintRange.SomePages;
workbook.PrintDialog = dialog;
PrintDocument pd = workbook.PrintDocument;
if (dialog.ShowDialog() == DialogResult.OK)
{ pd.Print(); }
[VB.NET]
Dim workbook As Workbook =  New Workbook() 
workbook.LoadFromFile(InputFile)
Dim dialog As PrintDialog =  New PrintDialog() 
dialog.AllowPrintToFile = True
dialog.AllowCurrentPage = True
dialog.AllowSomePages = True
dialog.AllowSelection = True
dialog.UseEXDialog = True
dialog.PrinterSettings.Duplex = Duplex.Simplex
dialog.PrinterSettings.FromPage = 0
dialog.PrinterSettings.ToPage = 8
dialog.PrinterSettings.PrintRange = PrintRange.SomePages
workbook.PrintDialog = dialog
Dim pd As PrintDocument =  workbook.PrintDocument 
If dialog.ShowDialog() = DialogResult.OK Then
	 pd.Print()
End If