Home » excel » c# – Excel Interop Print

c# – Excel Interop Print

Posted by: admin March 9, 2020 Leave a comment

Questions:

I need to print a selected area of an excel sheet (which I selected with Range.Select()) using the following print settings:

Printer: Microsoft XPS Document Writer
Print Selection
Landscape Orientation
A4
Normal Margins
Fit Sheet on One Page

How can I achieve this using _Worksheet.PrintOut or _Worksheet.PrintOutEx?

Thanks in advance!

How to&Answers:

Try this (TRIED AND TESTED)

I am assuming that you have set reference to Excel and have already declared your objects like

Microsoft.Office.Interop.Excel.Application xlexcel;
Microsoft.Office.Interop.Excel.Workbook xlWorkBook;
Microsoft.Office.Interop.Excel.Worksheet xlWorkSheet;
Microsoft.Office.Interop.Excel.Range xlRange;
object misValue = System.Reflection.Missing.Value;

This goes in the later part of the code.

// Get the current printer
string Defprinter = null;
Defprinter = xlexcel.ActivePrinter;

// Set the printer to Microsoft XPS Document Writer
xlexcel.ActivePrinter = "Microsoft XPS Document Writer on Ne01:";

// Setup our sheet
var _with1 = xlWorkSheet.PageSetup;
// A4 papersize
_with1.PaperSize = Excel.XlPaperSize.xlPaperA4;
// Landscape orientation
_with1.Orientation = Excel.XlPageOrientation.xlLandscape;
// Fit Sheet on One Page 
_with1.FitToPagesWide = 1;
_with1.FitToPagesTall = 1;
// Normal Margins
_with1.LeftMargin = xlexcel.InchesToPoints(0.7);
_with1.RightMargin = xlexcel.InchesToPoints(0.7);
_with1.TopMargin = xlexcel.InchesToPoints(0.75);
_with1.BottomMargin = xlexcel.InchesToPoints(0.75);
_with1.HeaderMargin = xlexcel.InchesToPoints(0.3);
_with1.FooterMargin = xlexcel.InchesToPoints(0.3);

// Print the range
xlRange.PrintOutEx(misValue, misValue, misValue, misValue, 
misValue, misValue, misValue, misValue);

// Set printer back to what it was
xlexcel.ActivePrinter = Defprinter;

Answer:

For the ‘Fit Sheet on One Page’ to work we should also set the Zoom property to false.

// Fit Sheet on One Page

_with1.FitToPagesWide = 1;

_with1.FitToPagesTall = 1;

_with1.Zoom = False;