Archive

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)

How to use Worksheet.PivotTableWizard in the xlwings API way

The PivotTableWizard method in Excel’s object model is a legacy but powerful tool for programmatically creating pivot tables. In xlwings, this functionality is accessed through the api property, which provides direct access to the underlying Excel object model. The PivotTableWizard method belongs to the Worksheet object and allows for the dynamic generation of pivot tables based on specified source data and parameters. It is particularly useful when you need to automate the creation of pivot tables with custom configurations that might be cumbersome to set up manually through the Excel interface.

The syntax for calling PivotTableWizard via xlwings is as follows:
worksheet.api.PivotTableWizard(SourceType, SourceData, TableDestination, TableName, RowGrand, ColumnGrand, SaveData, HasAutoFormat, AutoPage, Reserved, BackgroundQuery, OptimizeCache, PageFieldOrder, PageFieldWrapCount, ReadData, Connection)
Here, worksheet is an xlwings Sheet object. The parameters control various aspects of the pivot table creation. Key parameters include:

  • SourceType: Specifies the source of data. It can be xlDatabase (Excel range), xlExternal (external data source), xlConsolidation (multiple ranges), or xlScenario. Commonly, xlDatabase is used.
  • SourceData: The range containing the source data. This can be a Range object or a string address.
  • TableDestination: A Range object specifying the top-left cell where the pivot table should be placed.
  • TableName: A string for the pivot table’s name.
    Other parameters like RowGrand and ColumnGrand control the display of grand totals, while SaveData determines if data is saved with the pivot table. Many parameters are optional and can be omitted by using None in Python.

For example, consider creating a pivot table from data in Sheet1 ranging from A1 to D100, placing the pivot table in Sheet2 starting at cell A3. The following xlwings code demonstrates this:

import xlwings as xw
from xlwings.constants import PivotTableSourceType

# Connect to the active workbook
wb = xw.Book.active
source_sheet = wb.sheets['Sheet1']
destination_sheet = wb.sheets['Sheet2']

# Define source data range
source_range = source_sheet.range('A1:D100')

# Create the pivot table
destination_sheet.api.PivotTableWizard(
SourceType=PivotTableSourceType.xlDatabase,
SourceData=source_range.api,
TableDestination=destination_sheet.range('A3').api,
TableName='SalesPivotTable',
RowGrand=True,
ColumnGrand=True
)

How to use Worksheet.PivotTables in the xlwings API way

The PivotTables member of the Worksheet object in the Excel object model is a collection that provides access to all pivot tables on a specific worksheet. Through the xlwings API, this collection allows for programmatic control over pivot tables, enabling tasks such as creating new pivot tables, modifying existing ones, refreshing data, or extracting information. This is particularly useful for automating reporting, data analysis workflows, and ensuring that pivot tables reflect the latest data without manual intervention.

In xlwings, the PivotTables collection is accessed via a Worksheet object. The syntax is straightforward: ws.pivot_tables, where ws is an xlwings Sheet object representing the worksheet. This returns a collection of PivotTable objects. You can iterate through this collection or access a specific pivot table by its name using indexing, e.g., ws.pivot_tables['PivotTable1'].

Key methods and properties available through the PivotTable object in xlwings include:

  • refresh(): Updates the pivot table with the latest data from its source.
  • name: Gets or sets the name of the pivot table.
  • source_data: Gets or sets the range address of the source data (e.g., 'Sheet1!$A$1:$D$100').
  • table_range1: Returns an xlwings Range object representing the entire pivot table, useful for copying or formatting.

For example, to list all pivot tables on a worksheet and refresh them:

import xlwings as xw

# Connect to the active workbook
wb = xw.books.active
ws = wb.sheets['SalesData']

# Iterate through all pivot tables and refresh each
for pt in ws.pivot_tables:
    print(f"Refreshing Pivot Table: {pt.name}")
    pt.refresh()

To create a new pivot table using xlwings, you typically use the api property to access the underlying Excel VBA object model, as xlwings does not have a dedicated high-level method for this. Here is an example that creates a pivot table from a source range:

import xlwings as xw

wb = xw.books.active
source_ws = wb.sheets['TransactionData']
pivot_ws = wb.sheets['Analysis']

# Define the source data range
source_range = source_ws.range('A1').expand('table')

# Use the Excel API via xlwings to create the pivot table
pc = wb.api.PivotCaches().Create(SourceType=xw.constants.PivotTableSourceType.xlDatabase,
SourceData=source_range.api)
pt = pc.CreatePivotTable(TableDestination=pivot_ws.range('A3').api,
TableName='MonthlySales')

# Configure the pivot table fields (using the Excel API)
pt.PivotFields('Region').Orientation = xw.constants.PivotFieldOrientation.xlRowField
pt.PivotFields('Month').Orientation = xw.constants.PivotFieldOrientation.xlColumnField
pt.PivotFields('Sales').Orientation = xw.constants.PivotFieldOrientation.xlDataField

Another common task is to modify an existing pivot table’s data source. Suppose you have extended your source data; you can update the pivot cache accordingly:

ws = xw.books.active.sheets['Dashboard']
pt = ws.pivot_tables[0] # Access the first pivot table in the collection

# Update the source data range to include new rows/columns
new_source_range = "TransactionData!$A$1:$F$500"
pt.source_data = new_source_range
pt.refresh()

How to use Worksheet.PasteSpecial in the xlwings API way

The PasteSpecial method of the Worksheet object in Excel is a powerful feature for pasting data with specific attributes, such as values, formats, or formulas, rather than a simple copy-paste. In xlwings, this functionality is accessible through the api property, which provides direct access to the underlying Excel object model. This allows for precise control over how data is transferred between ranges or applications, making it essential for tasks like consolidating reports, applying number formats, or skipping blanks during data integration.

Functionality
The primary purpose of PasteSpecial is to paste clipboard contents into a worksheet range with specified options. Unlike the standard Paste method, it enables selective pasting—for example, pasting only the values from copied cells while discarding formulas, or pasting only the column widths. This is particularly useful when you need to manipulate data without altering underlying formulas or when preparing data for presentation.

Syntax
In xlwings, you call PasteSpecial via the Excel object model. The method is applied to a Range object where the paste will occur. The basic syntax is:

sheet.range("A1").api.PasteSpecial(Paste, Operation, SkipBlanks, Transpose)

The parameters are:

  • Paste: Specifies the part of the copied data to paste. It is an enumeration from the XlPasteType constants. Common values include:
  • xlPasteAll (-4104): Pastes everything.
  • xlPasteValues (-4163): Pastes only values.
  • xlPasteFormats (-4122): Pastes only formats.
  • xlPasteFormulas (-4123): Pastes only formulas.
  • Operation: Optional. Specifies a mathematical operation to apply during the paste, from the XlPasteSpecialOperation constants. For example, xlPasteSpecialOperationAdd (2) adds the copied data to the destination values. If omitted, no operation is performed.
  • SkipBlanks: Optional. A boolean (True or False) that, when set to True, prevents blank cells from the copied range from overwriting existing data in the destination.
  • Transpose: Optional. A boolean that, when True, transposes rows and columns during the paste.

These parameters are passed as keyword arguments in Python, and you can refer to Excel’s VBA documentation for exact constant values. In practice, you often use numeric equivalents (e.g., -4163 for xlPasteValues).

Code Examples
Here are practical xlwings API examples demonstrating PasteSpecial:

  1. Paste Values Only: Copy data from one range and paste only the values into another, ignoring formulas and formats.
import xlwings as xw
wb = xw.Book("example.xlsx")
sheet = wb.sheets["Sheet1"]
# Copy data from A1:B5
sheet.range("A1:B5").api.Copy()
# Paste only values into D1
sheet.range("D1").api.PasteSpecial(Paste=-4163) # xlPasteValues
# Clear clipboard to avoid persistent paste prompts
wb.app.api.CutCopyMode = False
  1. Paste Formats and Transpose: Copy a range and paste only its formatting to a new location, while also transposing the layout.
import xlwings as xw
wb = xw.Book("report.xlsx")
sheet = wb.sheets["Data"]
# Copy the header range
sheet.range("A1:D1").api.Copy()
# Paste formats with transposition to A10
sheet.range("A10").api.PasteSpecial(Paste=-4122, Transpose=True) # xlPasteFormats
wb.app.api.CutCopyMode = False
  1. Paste with Operation and Skip Blanks: Copy a range of numbers and add them to an existing dataset, skipping any blanks in the copied data.
import xlwings as xw
wb = xw.Book("budget.xlsx")
sheet = wb.sheets["Summary"]
# Copy values from a source range
sheet.range("F1:F10").api.Copy()
# Paste with addition operation, skipping blanks
sheet.range("G1").api.PasteSpecial(Paste=-4163, Operation=2, SkipBlanks=True)
wb.app.api.CutCopyMode = False

How to use Worksheet.Paste in the xlwings API way

The Paste method in the Worksheet object of the xlwings API is a powerful feature for transferring data from the clipboard directly into an Excel worksheet. This method is particularly useful when you need to paste data that has been copied from other applications or within Excel itself, automating the process without manual intervention. It leverages the underlying Excel object model, providing a seamless way to integrate clipboard operations into your Python scripts.

Functionality:
The primary function of the Paste method is to insert the contents of the clipboard at a specified location in the worksheet. It can handle various data types, including text, numbers, formulas, and formatting, depending on what is currently stored in the clipboard. This method is essential for automating data import tasks, such as pasting data from external sources like web pages or other documents.

Syntax:
In xlwings, the Paste method is called on a Worksheet object. The basic syntax is:

worksheet.api.Paste(Destination)
  • worksheet: An xlwings Worksheet object representing the target worksheet.
  • Destination: (Optional) A Range object specifying the top-left cell where the pasted data will be placed. If omitted, the paste operation occurs at the current selection in the worksheet. In xlwings, you can specify the destination using worksheet.range('A1') or similar.

Note: The Paste method is accessed via the .api property in xlwings, which provides direct access to the underlying Excel object model (e.g., VBA methods). This is because Paste is not natively wrapped in the high-level xlwings API but is available through the low-level API.

Parameters:
The Destination parameter is optional and can be set as follows:

  • If provided, it must be an Excel Range object (accessed via xlwings range method). For example, worksheet.range('B2') would start pasting at cell B2.
  • If not provided, the paste uses the currently selected cell in Excel, which may be unpredictable in automated scripts. It is generally recommended to specify the destination explicitly.

Code Examples:
Here are practical examples of using the Paste method with xlwings:

  1. Basic Paste Operation: Copy data from another workbook and paste it into a specific cell.
import xlwings as xw

# Open the source and target workbooks
source_wb = xw.Book('source.xlsx')
target_wb = xw.Book('target.xlsx')

# Copy data from source worksheet (e.g., range A1:C10)
source_wb.sheets['Sheet1'].range('A1:C10').copy()

# Paste the copied data into target worksheet at cell D5
target_sheet = target_wb.sheets['Sheet1']
target_sheet.api.Paste(Destination=target_sheet.range('D5').api)
  1. Pasting Without Specifying Destination: This uses the current selection, which can be set beforehand.
import xlwings as xw

wb = xw.Book('data.xlsx')
sheet = wb.sheets['Sheet1']

# Copy data from a range
sheet.range('A1:A5').copy()

# Select a cell where you want to paste (e.g., C1)
sheet.range('C1').select()

# Paste at the selected location
sheet.api.Paste()
  1. Automating Data Import from Clipboard: Assume data is copied from an external application like a web browser.
import xlwings as xw
import pyperclip # Third-party library to access clipboard

# Simulate copying data to clipboard (in real use, data might be copied manually or via automation)
pyperclip.copy('Sample text from clipboard')

# Open Excel and paste the clipboard content
wb = xw.Book()
sheet = wb.sheets[0]
sheet.api.Paste(Destination=sheet.range('A1').api)

# This will paste "Sample text from clipboard" into cell A1