The PrintOut member of the Range object in Excel’s object model is a method used to print a specified range of cells. In xlwings, this functionality is accessible through the api property, which provides direct access to the underlying Excel object model. This method is particularly useful for automating the printing of specific data sections, reports, or charts directly from Python scripts, enabling seamless integration of Excel printing tasks into automated workflows.
Functionality
The PrintOut method prints the specified range. It allows control over various print settings such as the number of copies, whether to collate, and the printer to use. This can help in generating hard copies of data without manual intervention, ideal for batch processing or scheduled reporting.
Syntax
In xlwings, the syntax for calling PrintOut is:
range_object.api.PrintOut(From, To, Copies, Preview, ActivePrinter, PrintToFile, Collate, PrToFileName)
Here, range_object is an xlwings Range object (e.g., sheet.range('A1:D10')). The parameters are optional and map directly to Excel’s PrintOut method arguments:
From: The starting page number to print. If omitted, printing starts from the beginning.To: The ending page number to print. If omitted, printing goes to the end.Copies: The number of copies to print. Default is 1.Preview: IfTrue, Excel will show the print preview instead of printing immediately. Default isFalse.ActivePrinter: A string specifying the printer name to use. If omitted, the default printer is used.PrintToFile: IfTrue, the output is sent to a file. Default isFalse.Collate: IfTrue, copies are collated when printing multiple copies. Default isTrue.PrToFileName: The file name ifPrintToFileis set toTrue. If omitted, Excel prompts for a file name.
Code Examples
- Basic printing of a range:
This example prints the range A1 to D10 on the active sheet with default settings.
import xlwings as xw
# Connect to the active workbook and sheet
wb = xw.books.active
sheet = wb.sheets.active
# Define the range and print
print_range = sheet.range('A1:D10')
print_range.api.PrintOut()
- Printing multiple copies with collation:
Here, two collated copies of the range B2:F20 are printed.
import xlwings as xw
wb = xw.books.active
sheet = wb.sheets.active
print_range = sheet.range('B2:F20')
print_range.api.PrintOut(Copies=2, Collate=True)
- Printing to a file:
This sends the output of the range A1:Z100 to a PDF file named “report.pdf” without showing preview.
import xlwings as xw
wb = xw.books.active
sheet = wb.sheets.active
print_range = sheet.range('A1:Z100')
print_range.api.PrintOut(PrintToFile=True, PrToFileName="report.pdf", Preview=False)
- Using print preview:
To preview the print output for the range C5:G15 before printing.
import xlwings as xw
wb = xw.books.active
sheet = wb.sheets.active
print_range = sheet.range('C5:G15')
print_range.api.PrintOut(Preview=True)
Leave a Reply