Archive

How to use Worksheet.ShowDataForm in the xlwings API way

The ShowDataForm method in the Worksheet object is a powerful feature that allows developers to programmatically display Excel’s built-in data form for a specific range or list. This data form provides a user-friendly dialog box for entering, editing, and deleting records in a structured table, which is particularly useful for databases or lists where manual cell-by-cell editing can be error-prone. In xlwings, this method enables automation of form display, integrating seamlessly with Python scripts to enhance data management workflows within Excel.

Functionality
The primary function of ShowDataForm is to open Excel’s data form for a worksheet. This form automatically detects the range of contiguous data (typically a table with headers) and presents it in a modal dialog. Users can navigate through records, add new ones, modify existing entries, or delete data without directly interacting with the worksheet grid. It simplifies data entry tasks, especially for non-technical users, by providing a clean, form-based interface. In automation contexts, calling this method via xlwings can trigger the form as part of a larger process, such as after data validation or before saving a workbook.

Syntax
In xlwings, the ShowDataForm method is accessed through a Worksheet object. The API call follows the pattern below, with no required parameters, as it defaults to using the current region of the active cell or a specified range if set. The method is a member of the worksheet instance, and its invocation is straightforward.

worksheet.api.ShowDataForm()
  • Parameters: This method does not accept any parameters in xlwings. It relies on Excel’s internal logic to determine the data range, typically based on the active cell’s current region (a contiguous block of cells surrounded by empty rows and columns). If a specific range needs to be targeted, ensure the active cell is within that range before calling the method, or use Excel’s object model to set the range programmatically via other properties (e.g., Range selection).
  • Returns: The method does not return a value; it simply displays the data form as a modal dialog. User interactions in the form (like edits or additions) are directly reflected in the worksheet upon closure.

Example Usage
Below is a practical xlwings code example that demonstrates how to use ShowDataForm to open the data form for a worksheet. The example assumes an Excel workbook is already open or created via xlwings, and it targets a specific worksheet with existing data. The script automates the process of activating the worksheet and displaying the form, which can be integrated into larger automation tasks, such as data review steps.

import xlwings as xw

# Connect to an existing Excel workbook (adjust the path as needed)
wb = xw.Book('example.xlsx')

# Access a specific worksheet by name
ws = wb.sheets['DataSheet']

# Ensure the worksheet is active (optional, but good practice for form display)
ws.activate()

# Display the data form for the worksheet
ws.api.ShowDataForm()

How to use Worksheet.ShowAllData in the xlwings API way

The ShowAllData member of the Worksheet object in Excel is a method used to clear any filters that have been applied to an Excel table, list, or range on the specified worksheet. When filters are active, some rows may be hidden based on the filter criteria. Calling ShowAllData removes these filters, making all rows in the data range visible again. This is particularly useful in data analysis workflows when you need to reset the view to the full dataset after performing filtered operations or before applying new filters. It ensures that subsequent operations, such as sorting or calculations, consider the entire dataset unless otherwise specified.

In xlwings, the ShowAllData method is accessed through the api property of a Worksheet object, which provides direct access to the underlying Excel object model. The method does not take any parameters.

Syntax:

worksheet.api.ShowAllData()

Here, worksheet is an xlwings Worksheet object representing the Excel worksheet where you want to clear filters. The api property exposes the native Excel VBA object model, allowing you to call the ShowAllData method directly. Since no parameters are required, you simply invoke it without arguments.

Example:
Consider a scenario where you have an Excel workbook with a worksheet named “SalesData” containing a table with filters applied to certain columns. You want to clear all filters to display the full dataset. Below is an example using xlwings to achieve this:

import xlwings as xw

# Connect to the active Excel instance or open a specific workbook
app = xw.apps.active # Use the currently active Excel application
wb = app.books['SalesReport.xlsx'] # Specify your workbook name

# Access the worksheet by name
ws = wb.sheets['SalesData']

# Check if filters are applied (optional step, for demonstration)
# Note: There's no direct xlwings property to check filter status, so we rely on the Excel method.
try:
    # Attempt to show all data; if no filter is applied, this may raise an error.
    ws.api.ShowAllData()
    print("All filters cleared successfully.")
except Exception as e:
    # Handle cases where no filters are present or other errors occur
    print(f"No filters to clear or an error occurred: {e}")

# Perform further operations, such as sorting the entire dataset
ws.range('A1').current_region.api.Sort(Key1=ws.range('A2'), Order1=1) # Sort by column A ascending

# Save the workbook if needed
wb.save()

How to use Worksheet.SetBackgroundPicture in the xlwings API way

The SetBackgroundPicture method in the Worksheet object is a feature in Excel’s object model that allows developers to set a background image for a worksheet. This can enhance the visual appeal of spreadsheets, such as adding logos, watermarks, or decorative backgrounds for reports or dashboards. In xlwings, a Python library for interacting with Excel, this functionality is exposed through the api property, which provides direct access to Excel’s COM objects. Using SetBackgroundPicture, users can programmatically apply images to worksheet backgrounds, automating tasks that might otherwise require manual steps in Excel’s user interface.

Functionality:
The primary function of SetBackgroundPicture is to assign an image file as the background of a specific worksheet. This image is tiled across the entire sheet, meaning it repeats to cover the worksheet area. It’s important to note that setting a background picture does not affect cell formatting or data entry; the image appears behind the cells. However, background pictures are not printed by default in Excel, and they may impact performance if the image file is large. This method is useful for branding purposes or creating visually consistent templates in automated Excel reports.

Syntax in xlwings:
In xlwings, you can call SetBackgroundPicture through the api property of a Sheet object (which corresponds to a Worksheet in Excel). The syntax is as follows:

sheet.api.SetBackgroundPicture(Filename)
  • Parameters:
  • Filename (required): A string that specifies the path to the image file. This should be a full or relative path to a supported image format, such as JPEG, PNG, BMP, or GIF. The path must be accessible from the system where the Excel application is running.
  • Returns:
    This method does not return a value; it applies the background picture directly to the worksheet.
  • Notes:
  • If the file path is invalid or the image cannot be loaded, Excel may raise an error.
  • To remove an existing background picture, you can use sheet.api.SetBackgroundPicture("") with an empty string as the filename.
  • Background pictures are specific to each worksheet, so you need to call this method for each sheet individually.
  • In xlwings, ensure that the Excel application is visible or running in the background when executing this method, as it relies on COM interop.

Code Examples:
Below are practical examples using xlwings to set a background picture for a worksheet.

  1. Setting a Background Picture:
    This example assumes you have an Excel file open and want to set a background image for the active sheet.
import xlwings as xw

# Connect to the active Excel instance
app = xw.apps.active
workbook = app.books.active
sheet = workbook.sheets['Sheet1'] # Specify the worksheet name

# Set the background picture using an image file path
image_path = r'C:\Images\background.jpg' # Use raw string for Windows paths
sheet.api.SetBackgroundPicture(image_path)

# Save the workbook to persist changes
workbook.save()
  1. Removing a Background Picture:
    To clear the background picture from a worksheet, pass an empty string as the filename.
import xlwings as xw

# Connect to the active workbook and sheet
sheet = xw.books.active.sheets[0] # Access the first sheet

# Remove any existing background picture
sheet.api.SetBackgroundPicture("")

# Optionally, save the changes
xw.books.active.save()
  1. Setting Background Pictures for Multiple Sheets:
    You can loop through multiple worksheets in a workbook to apply the same background image.
import xlwings as xw

# Open a specific workbook
workbook = xw.Book('report.xlsx')
image_path = '/path/to/logo.png' # Adjust path for your system

# Apply background picture to all sheets
for sheet in workbook.sheets:
sheet.api.SetBackgroundPicture(image_path)

# Save and close if needed
workbook.save()
workbook.close()

How to use Worksheet.Select in the xlwings API way

The Select method of the Worksheet object in Excel is used to activate and highlight a specific worksheet, making it the active sheet in the workbook. This is particularly useful when you need to programmatically switch between sheets to perform operations like data entry, formatting, or analysis on a particular sheet without manual intervention. In xlwings, this functionality is accessed through the api property, which provides direct access to the underlying Excel object model, allowing for precise control over worksheet selection.

Syntax in xlwings:
The Select method is called on a worksheet object via its api attribute. The basic syntax is:

worksheet.api.Select(Replace)
  • Replace (Optional): A Boolean parameter that specifies whether the current selection should be replaced.
  • If True (or omitted, as the default is True), the selected worksheet replaces any previous selection, making it the only active sheet.
  • If False, the worksheet is added to the current selection, allowing multiple sheets to be selected simultaneously (e.g., for grouping or multi-sheet operations). This is applicable only if the workbook is not protected and the sheets are adjacent.

Example Usage:
Below are practical examples demonstrating how to use the Select method with xlwings.

  1. Basic Selection: Activate and select a single worksheet named “DataSheet”.
import xlwings as xw
# Connect to an existing workbook
wb = xw.Book("example.xlsx")
# Access the worksheet by name
ws = wb.sheets["DataSheet"]
# Select the worksheet, replacing any previous selection
ws.api.Select()
# Alternatively, explicitly set Replace to True
ws.api.Select(Replace=True)
  1. Selecting Multiple Sheets: Select multiple adjacent worksheets by adding to the selection without replacing it. This example selects “Sheet1” and “Sheet2” together.
import xlwings as xw
wb = xw.Book("example.xlsx")
# First, select Sheet1 with replacement
wb.sheets["Sheet1"].api.Select(Replace=True)
# Then, select Sheet2 without replacing, so both are selected
wb.sheets["Sheet2"].api.Select(Replace=False)
# Note: This requires the sheets to be next to each other in the workbook.
  1. Integration with Other Operations: Combine Select with other actions, such as formatting or data input, after making a worksheet active. Here, we select a sheet and then clear its contents.
import xlwings as xw
wb = xw.Book("example.xlsx")
ws = wb.sheets["Report"]
# Select the worksheet
ws.api.Select()
# Now perform an operation on the active sheet, like clearing cell A1 to D10
ws.range("A1:D10").clear()

How to use Worksheet.Scenarios in the xlwings API way

In Excel, a Scenario is a set of input values (called changing cells) that you can save and later substitute into a worksheet to see different outcomes. The Scenarios collection of a Worksheet object in Excel’s object model allows you to manage these saved scenarios. Through xlwings, you can programmatically access, create, modify, and apply these scenarios, enabling powerful what-if analysis automation within your Python scripts.

Functionality
The Scenarios member provides a way to interact with all scenarios defined on a specific worksheet. You can add new scenarios, retrieve existing ones, change their values, show (apply) a particular scenario, and delete scenarios. This is particularly useful for building financial models, project plans, or any analysis where you need to quickly switch between different sets of assumptions.

Syntax and Key Members
In xlwings, you access the Scenarios collection via the api property of a Sheet object (which corresponds to a Worksheet). The primary properties and methods include:

  • Accessing the Collection: sheet.api.Scenarios
  • Count Property: sheet.api.Scenarios.Count returns the number of scenarios on the sheet.
  • Item Method: sheet.api.Scenarios(Index) or sheet.api.Scenarios(Name) retrieves a specific Scenario object. Index can be the scenario’s number (1-based) or name.
  • Add Method: Used to create a new scenario.
sheet.api.Scenarios.Add(Name, ChangingCells, Values, Comment, Locked, Hidden)
  • Name (String, Required): The name for the new scenario.
  • ChangingCells (Object, Required): An xlwings Range object (e.g., sheet.range("B2:B3")), specifying the cells that will change.
  • Values (Variant, Optional): An array of values to be entered into the changing cells. If omitted, the current values in the cells are used.
  • Comment (String, Optional): A comment describing the scenario (up to 255 characters).
  • Locked (Boolean, Optional): True to prevent modifications when the sheet is protected.
  • Hidden (Boolean, Optional): True to hide the scenario when the sheet is protected.
  • A Scenario object itself has key methods like:
  • Show(): Applies the scenario’s values to the worksheet.
  • ChangeScenario(ChangingCells, Values): Modifies the scenario’s changing cells or values.
  • Delete(): Removes the scenario.

Code Examples

  1. Adding a New Scenario:
import xlwings as xw
wb = xw.Book("Analysis.xlsx")
sheet = wb.sheets["Sheet1"]

# Define changing cells and values
changing_cells = sheet.range("B2, B4") # Assumptions for Price and Units
scenario_values = [29.99, 1200]

# Add a "Best Case" scenario
sheet.api.Scenarios.Add(Name="Best Case",
ChangingCells=changing_cells,
Values=scenario_values,
Comment="Optimistic sales forecast")
  1. Applying (Showing) an Existing Scenario:
# Apply the "Worst Case" scenario to see its impact
try:
    sheet.api.Scenarios("Worst Case").Show()
    print("Applied 'Worst Case' scenario.")
except Exception as e:
    print(f"Scenario not found: {e}")
  1. Iterating Through and Managing Scenarios:
# List all scenarios and delete a specific one
scenarios = sheet.api.Scenarios
print(f"Number of scenarios: {scenarios.Count}")

for i in range(1, scenarios.Count + 1):
    scen = scenarios(i)
    print(f"{i}: {scen.Name} - {scen.Comment}")

# Delete the "Obsolete" scenario if it exists
if scenarios.Count > 0:
    for scen in scenarios:
        if scen.Name == "Obsolete":
            scen.Delete()
            print("Deleted 'Obsolete' scenario.")
            break
  1. Modifying a Scenario’s Values:
# Update the values for the "Base Case" scenario
target_scenario = sheet.api.Scenarios("Base Case")
new_changing_cells = sheet.range("B2:B3")
new_values = [25.50, 950]
target_scenario.ChangeScenario(ChangingCells=new_changing_cells, Values=new_values)

How to use Worksheet.SaveAs in the xlwings API way

The SaveAs method in the Worksheet object of the Excel object model is a powerful feature for saving a specific worksheet as a new workbook file. This is particularly useful in scenarios where you need to extract or archive a single sheet from a larger workbook, or when generating reports from a template. In xlwings, this functionality is accessed through the api property, which provides direct access to the underlying Excel object model, allowing for precise control similar to VBA.

The syntax for calling SaveAs via xlwings is: worksheet.api.SaveAs(Filename, FileFormat, Password, WriteResPassword, ReadOnlyRecommended, CreateBackup, AddToMru, TextCodepage, TextVisualLayout, Local). The key parameters are:

  • Filename: A string specifying the full path and name of the file to save. It is required.
  • FileFormat: A constant or number specifying the file format. Common values include 51 for .xlsx (Excel Workbook), 52 for .xlsm (Macro-Enabled Workbook), and 6 for .csv (CSV format). If omitted, the current file format is used.
  • Password: An optional string to set a password for opening the workbook.
  • WriteResPassword: An optional string to set a password for write reservation.
  • CreateBackup: If set to True, Excel creates a backup file.
  • Other parameters like ReadOnlyRecommended, AddToMru, TextCodepage, TextVisualLayout, and Local are less frequently used and often left as default.

For example, to save the active worksheet as a new Excel workbook in the .xlsx format to a specific directory, you can use the following xlwings code. This example assumes you have an existing workbook with a worksheet object referenced. The code saves the worksheet “DataSheet” as a separate file, ensuring the original workbook remains unchanged. It demonstrates setting a filename, specifying the file format, and optionally adding a password for protection. This method is efficient for automating report generation or data extraction tasks, as it leverages Excel’s native saving capabilities through a clean Python interface.

import xlwings as xw

# Connect to the active Excel instance or open a workbook
app = xw.apps.active
wb = app.books['OriginalWorkbook.xlsx']
ws = wb.sheets['DataSheet']

# Save the worksheet as a new workbook
new_file_path = r'C:\Reports\Extracted_DataSheet.xlsx'
ws.api.SaveAs(Filename=new_file_path, FileFormat=51) # 51 corresponds to .xlsx

# To save as a CSV file without a password
csv_path = r'C:\Reports\DataSheet.csv'
ws.api.SaveAs(Filename=csv_path, FileFormat=6) # 6 corresponds to CSV

# To save with a password for opening
protected_path = r'C:\Reports\Secure_DataSheet.xlsx'
ws.api.SaveAs(Filename=protected_path, FileFormat=51, Password='mysecret')

How to use Worksheet.ResetAllPageBreaks in the xlwings API way

The Worksheet.ResetAllPageBreaks method in Excel’s object model is a useful tool for managing print layout, specifically by removing all manually inserted page breaks on a specified worksheet. When preparing a document for printing, users often insert horizontal or vertical page breaks to control where pages end. Over time, a sheet can accumulate many such breaks, which may no longer be needed or could interfere with updated print settings. The ResetAllPageBreaks method clears all these user-defined page breaks at once, reverting the sheet to automatic page breaking based on current margins, paper size, and scaling. This is particularly helpful when you want to start fresh with page layout adjustments or ensure print output follows default pagination.

In xlwings, the API closely mirrors the Excel object model. To call this method, you access it through a Worksheet object. The syntax is straightforward as it does not take any parameters. The general format is:

worksheet.api.ResetAllPageBreaks()

Here, worksheet refers to an xlwings Worksheet object. The .api property provides direct access to the underlying Excel object model, allowing you to use native Excel methods like ResetAllPageBreaks. Since it is a method, you invoke it with parentheses. It affects only the worksheet it is called on and does not return a value.

Consider a scenario where you have an Excel workbook for monthly reports. After several rounds of manual page break adjustments, you want to clear them all to apply a new uniform print setup. The following xlwings code example demonstrates this:

import xlwings as xw

# Connect to the active Excel application or start a new one
app = xw.apps.active

# Open a specific workbook (adjust the path as needed)
wb = app.books.open('Monthly_Report.xlsx')

# Access the desired worksheet
ws = wb.sheets['DataSheet']

# Reset all manually inserted page breaks on this worksheet
ws.api.ResetAllPageBreaks()

# Save the workbook to persist changes
wb.save()

# Optionally, close the workbook and app
wb.close()
app.quit()

How to use Worksheet.Protect in the xlwings API way

The protect method of the Worksheet object in xlwings provides a way to secure a worksheet by preventing unauthorized changes. This is particularly useful when you want to share a workbook but restrict editing of specific cells, formulas, or structural elements. By protecting a worksheet, you can allow certain actions, such as selecting cells, while blocking others, like modifying locked cells. In xlwings, this method wraps the corresponding functionality in the Excel object model, offering a programmatic approach to worksheet protection directly from Python.

The syntax for the protect method in xlwings is as follows:

worksheet.api.Protect(Password, DrawingObjects, Contents, Scenarios, UserInterfaceOnly, AllowFormattingCells, AllowFormattingColumns, AllowFormattingRows, AllowInsertingColumns, AllowInsertingRows, AllowInsertingHyperlinks, AllowDeletingColumns, AllowDeletingRows, AllowSorting, AllowFiltering, AllowUsingPivotTables)

Here, worksheet is an xlwings Sheet object representing the target worksheet. The parameters correspond to those in the Excel VBA Protect method, with most being optional boolean values that default to True or False depending on the action. Key parameters include:

  • Password: A string to set a password for unprotecting the sheet (optional; if omitted, no password is set).
  • Contents: If True (default), protects the contents (locked cells) of the worksheet.
  • UserInterfaceOnly: If True, protection applies only to the UI, allowing macros to make changes via code; defaults to False.
  • AllowFormattingCells, AllowFormattingColumns, etc.: These boolean parameters control specific user permissions, such as allowing cell formatting or inserting rows; most default to False when the sheet is protected.

For example, to protect a worksheet with a password while allowing users to format cells and sort data, you can set AllowFormattingCells and AllowSorting to True. Note that in xlwings, you access this via the .api property to call the underlying Excel object model method, as xlwings does not have a native wrapper for all protection options in its high-level API.

Below are xlwings API code examples demonstrating the use of the protect method:

  1. Basic protection without a password: This protects the worksheet with default settings, preventing edits to locked cells.
import xlwings as xw
wb = xw.Book('example.xlsx')
ws = wb.sheets['Sheet1']
ws.api.Protect()
  1. Protection with a password and specific allowances: Here, a password “mypass123” is set, and users are permitted to format cells and insert hyperlinks, while other actions are restricted.
ws.api.Protect(Password='mypass123', AllowFormattingCells=True, AllowInsertingHyperlinks=True)
  1. UI-only protection for macro flexibility: This protects the worksheet in the user interface but allows VBA or xlwings macros to modify it programmatically, without a password.
ws.api.Protect(UserInterfaceOnly=True)
  1. Disabling protection: To unprotect a worksheet, use the Unprotect method. If a password was set, provide it as an argument.
ws.api.Unprotect('mypass123') # If password was used
ws.api.Unprotect() # If no password was set

How to use Worksheet.PrintPreview in the xlwings API way

The PrintPreview method in the Excel object model, accessible via the Worksheet object in xlwings, is a powerful feature for generating a print preview of a worksheet without physically printing it. This allows users to visually inspect the layout, page breaks, headers, footers, and overall formatting before committing to a print job, ensuring that the output matches expectations and conserving resources by avoiding unnecessary prints. In xlwings, this functionality is exposed through the api property, which provides direct access to the underlying Excel object model, enabling precise control over the print preview process.

Functionality:
The primary function of the PrintPreview method is to display the print preview dialog for the specified worksheet. This dialog shows exactly how the worksheet will appear when printed, based on the current page setup settings such as margins, orientation, scaling, and print area. It is an interactive preview, allowing users to navigate through pages, zoom in and out, and access print settings directly from the preview window. This is particularly useful for debugging complex reports or dashboards to ensure all elements are correctly positioned and formatted for hard copy.

Syntax:
In xlwings, the method is called via the Excel object model’s API. The syntax is:

worksheet.api.PrintPreview()

This method does not take any parameters. It is invoked directly on the worksheet object’s api property, which represents the native Excel Worksheet COM object. The call immediately opens the print preview window for that specific worksheet.

Code Example:
Below is a practical example demonstrating how to use the PrintPreview method in xlwings. This script assumes you have an Excel workbook open or will open one, select a worksheet, and then trigger the print preview.

import xlwings as xw

# Connect to the active Excel instance or start a new one
app = xw.apps.active

# Open a workbook (replace with your file path)
wb = app.books.open(r'C:\Path\To\Your\Workbook.xlsx')

# Access a specific worksheet by name or index
ws = wb.sheets['Sheet1'] # or wb.sheets[0]

# Display the print preview for the worksheet
ws.api.PrintPreview()

# Note: The script will pause while the print preview window is open.
# The user must manually close the preview to continue execution.

# To close the workbook without saving (optional)
wb.close()

How to use Worksheet.PrintOut in the xlwings API way

The PrintOut method of the Worksheet object in the Excel object model is a powerful feature for programmatically printing worksheets. In xlwings, this functionality is exposed through the api property, which provides direct access to the underlying Excel VBA object model. This allows for precise control over printing parameters, enabling automation of printing tasks directly from Python scripts.

Functionality
The PrintOut method prints the specified worksheet. It offers a range of optional parameters to control aspects such as the number of copies, print preview, printer selection, print range, and output to a file. This is essential for automating report generation, batch printing, or creating printed outputs from data processed in Python.

Syntax
In xlwings, the method is accessed via the worksheet’s api object. The full syntax, with parameters mapped from the VBA method, is as follows:
worksheet.api.PrintOut(From, To, Copies, Preview, ActivePrinter, PrintToFile, Collate, PrToFileName, IgnorePrintAreas)
Where:

  • From: (Optional) The page number from which to start printing. If omitted, printing starts from the beginning.
  • To: (Optional) The page number on which to stop printing. If omitted, printing goes to the end.
  • Copies: (Optional) The number of copies to print. If omitted, one copy is printed.
  • Preview: (Optional) True to have Excel invoke print preview before printing. False (default) to print immediately.
  • ActivePrinter: (Optional) Sets the name of the active printer.
  • PrintToFile: (Optional) True to print to a file. If PrToFileName is not specified, Excel prompts the user for the output filename.
  • Collate: (Optional) True (default) to collate multiple copies.
  • PrToFileName: (Optional) If PrintToFile is set to True, this specifies the path and filename of the output file (e.g., "C:\Output.pdf").
  • IgnorePrintAreas: (Optional) True to ignore any print areas set in the worksheet and print the entire sheet.

Code Examples

  1. Basic Print: Print the active worksheet immediately to the default printer.
import xlwings as xw
wb = xw.Book("report.xlsx")
ws = wb.sheets["Data"]
ws.api.PrintOut()
  1. Print with Preview and Copies: Print two collated copies of the worksheet after showing the print preview.
ws.api.PrintOut(Copies=2, Preview=True, Collate=True)
  1. Print Specific Pages: Print only pages 2 through 4 of the worksheet.
ws.api.PrintOut(From=2, To=4)
  1. Print to PDF File: Print the entire worksheet to a PDF file, ignoring any set print area.
output_path = r"C:\Reports\output.pdf"
ws.api.PrintOut(PrintToFile=True, PrToFileName=output_path, IgnorePrintAreas=True)
  1. Using Named Arguments for Clarity: Explicitly naming arguments is recommended for readability.
ws.api.PrintOut(From=1, To=1, Copies=1, Preview=False, Collate=True, IgnorePrintAreas=False)