Blog

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

How to use Worksheet.OLEObjects in the xlwings API way

The OLEObjects member of the Worksheet object in Excel represents a collection of all OLE objects (such as embedded documents, ActiveX controls, or other insertable objects) on a specific worksheet. In xlwings, this collection is accessible via the api property, which provides direct access to the underlying Excel object model. This allows for programmatic control over embedded objects, including enumeration, modification, and interaction with OLE controls within a workbook.

Functionality:
The primary use of the OLEObjects collection in xlwings is to manage embedded OLE objects. You can count the objects, retrieve a specific object by its index or name, modify properties (e.g., size, placement), or even invoke methods associated with ActiveX controls. This is particularly useful for automating dashboards or forms that contain interactive elements like buttons, list boxes, or embedded charts from other applications.

Syntax:
Accessing the OLEObjects collection in xlwings follows the pattern: worksheet.api.OLEObjects. This returns a collection object. To reference a specific OLE object, you can use:

  • worksheet.api.OLEObjects(Index) where Index is the object’s numeric position (1-based) or its name as a string.
  • worksheet.api.OLEObjects.Item(Index) which is functionally equivalent.

Common properties and methods of an OLE object (returned from the collection) include:

  • Name: Gets or sets the object’s name.
  • Left, Top, Width, Height: Control the object’s position and dimensions in points.
  • Object: Provides access to the underlying OLE object’s native interface (e.g., for an ActiveX control, you can access its specific properties).
  • Delete(): Removes the object from the worksheet.

Code Examples:

  1. List all OLE objects on a worksheet:
import xlwings as xw
wb = xw.Book('workbook.xlsx')
ws = wb.sheets['Sheet1']
ole_objects = ws.api.OLEObjects
count = ole_objects.Count
print(f"Number of OLE objects: {count}")
for i in range(1, count + 1):
    obj = ole_objects(i)
    print(f"Object {i}: Name='{obj.Name}', Type='{obj.progID}'")
  1. Resize and reposition an OLE object by name:
# Assume an embedded Word document object named "DocObject1"
obj = ws.api.OLEObjects("DocObject1")
obj.Left = 100 # Points from left edge
obj.Top = 50 # Points from top
obj.Width = 200
obj.Height = 150
  1. Interact with an ActiveX command button:
# Access the button, then its specific properties via the Object property
button = ws.api.OLEObjects("CommandButton1")
# Change the button caption
button.Object.Caption = "Click Me"
# The Object property exposes the ActiveX control's native interface
  1. Delete all OLE objects on a sheet:
ole_objects = ws.api.OLEObjects
for i in range(ole_objects.Count, 0, -1): # Iterate backwards when deleting
    ole_objects(i).Delete()

How to use Worksheet.Move in the xlwings API way

The Move member of the Worksheet object in the Excel object model, accessible via the xlwings library in Python, provides a programmatic way to reposition a worksheet within its workbook. This functionality is essential for organizing workbook structure, such as reordering sheets for logical presentation or moving a newly created sheet to a specific location. Unlike simply activating a sheet, the Move method physically changes the sheet’s index in the workbook’s tab order.

In xlwings, the method is accessed through a Sheet object (which represents a Worksheet). The core syntax for its API call is:

sheet.move(before, after)

Both parameters, before and after, are optional but mutually exclusive—you should specify only one. They accept either an xlwings Sheet object or an integer index.

  • before: The sheet before which the current sheet will be placed. If specified as a Sheet object, the moved sheet will be positioned immediately before that specific sheet. If specified as an integer (1-based index), the moved sheet will be moved to a position before the sheet currently at that index.
  • after: The sheet after which the current sheet will be placed. If specified as a Sheet object, the moved sheet will be positioned immediately after that specific sheet. If specified as an integer (1-based index), the moved sheet will be moved to a position after the sheet currently at that index.

If neither before nor after is specified, Excel will create a new workbook containing only the moved worksheet. The following table summarizes the behavior:

Parameter ProvidedResulting Action
before=targetMoves the sheet to a position immediately before the target sheet.
after=targetMoves the sheet to a position immediately after the target sheet.
Neither parameterMoves the sheet to a new, single-sheet workbook.

Code Examples:

  1. Move a sheet to the beginning of the workbook (before the first sheet):
import xlwings as xw
wb = xw.Book("report.xlsx")
sheet_to_move = wb.sheets["DataSheet"]
first_sheet = wb.sheets[0] # Index 0 refers to the first sheet
sheet_to_move.move(before=first_sheet)
  1. Move a sheet to the end of the workbook (after the last sheet):
import xlwings as xw
wb = xw.Book()
summary_sheet = wb.sheets.add("Summary")
last_sheet = wb.sheets[-1] # Index -1 refers to the last sheet
summary_sheet.move(after=last_sheet)
  1. Move a sheet to a specific index position (e.g., to become the third sheet):
import xlwings as xw
wb = xw.Book()
analysis_sheet = wb.sheets["Analysis"]
# To place it as the third sheet, move it before the current third sheet.
# Index is 1-based in the `move` method context for this operation.
analysis_sheet.move(before=3)
  1. Move a sheet relative to another named sheet:
import xlwings as xw
wb = xw.Book("dashboard.xlsx")
chart_sheet = wb.sheets["Charts"]
pivot_sheet = wb.sheets["PivotTables"]
# Place the Charts sheet right after the PivotTables sheet
chart_sheet.move(after=pivot_sheet)

How to use Worksheet.ExportAsFixedFormat in the xlwings API way

The ExportAsFixedFormat member of the Worksheet object in Excel’s object model is a method that enables the conversion of a worksheet into a fixed-layout format, such as PDF or XPS, directly from an Excel file. In xlwings, this functionality is exposed through the api property, which provides direct access to the underlying Excel object model. This method is particularly useful for automating report generation, distributing documents in a non-editable format, or archiving sheets with precise formatting preserved.

Functionality:
The primary purpose of ExportAsFixedFormat is to export a worksheet to a fixed-format file. It supports formats including PDF and XPS, ensuring that the layout, fonts, and graphics are maintained as they appear in Excel. This is essential for creating professional documents that require consistent presentation across different devices and platforms.

Syntax in xlwings:
In xlwings, you call this method via the api property of a Worksheet object. The basic syntax is:

worksheet.api.ExportAsFixedFormat(Type, Filename, Quality, IncludeDocProperties, IgnorePrintAreas, From, To, OpenAfterPublish, FixedFormatExtClassPtr)

Here, worksheet refers to the xlwings Worksheet object. The parameters are as follows:

  • Type: Specifies the format type. Use 0 for PDF or 1 for XPS.
  • Filename: A string representing the full path and name of the output file (e.g., r'C:\Reports\output.pdf'). If omitted, Excel uses the default name.
  • Quality: Optional. Sets the quality of the output. Use 0 for Standard or 1 for Minimum size.
  • IncludeDocProperties: Optional. True to include document properties, False otherwise.
  • IgnorePrintAreas: Optional. True to ignore any set print areas, False to use them.
  • From and To: Optional. Integers specifying the page range to export (e.g., From=1, To=3). If not specified, all pages are exported.
  • OpenAfterPublish: Optional. True to open the file after export, False otherwise.
  • FixedFormatExtClassPtr: Optional. A pointer for extended format classes, typically left as None.

Most parameters are optional; in practice, only Type and Filename are commonly required. For example, to export as PDF with default settings, you might specify just these two.

Code Example:
Below is an xlwings code instance that demonstrates exporting the active worksheet to a PDF file. This example assumes Excel is already open with a workbook, and it sets a few optional parameters for clarity.

import xlwings as xw

# Connect to the active Excel instance
app = xw.apps.active
wb = app.books.active
ws = wb.sheets.active

# Export the active worksheet to PDF
output_path = r'C:\Users\Public\Documents\Monthly_Report.pdf'
ws.api.ExportAsFixedFormat(
Type=0, # 0 for PDF
Filename=output_path,
Quality=0, # Standard quality
IncludeDocProperties=True,
IgnorePrintAreas=False,
OpenAfterPublish=False
)

print(f"Worksheet exported to {output_path}")

How to use Worksheet.Evaluate in the xlwings API way

The Evaluate method of the Worksheet object in Excel is a powerful tool that allows you to evaluate a Microsoft Excel expression or a name and return the resulting value. In xlwings, this functionality is exposed through the api property, which provides direct access to the underlying Excel object model. This method is particularly useful for calculating formulas or expressions that are provided as strings, without the need to write them into a cell first. It can handle complex expressions, including those with functions and references, and return the computed result directly to your Python code.

Functionality:
The primary function of Evaluate is to compute the result of an Excel formula or expression given as a string. This is equivalent to typing the formula into the Excel formula bar and pressing Enter, but it is done programmatically. It can evaluate simple arithmetic, Excel functions, named ranges, and cell references. This is efficient for one-off calculations where you do not want to modify the worksheet.

Syntax in xlwings:
In xlwings, you access the Evaluate method through the api property of a Sheet object (which corresponds to a Worksheet). The general syntax is:

result = sheet.api.Evaluate(expression)
  • sheet: This is an xlwings Sheet object representing the worksheet where the evaluation context is considered (important for relative references).
  • expression (required): A string that contains the Excel formula or expression to be evaluated. This can be any valid Excel formula, such as "SUM(A1:A10)", "2+2", or "A1*B1". The string must be formatted exactly as it would be in Excel, using English function names and comma separators by default (depending on the system’s locale settings).

Parameters:
The Evaluate method takes a single parameter:

  • Expression: A string that is a valid Excel formula. It can include:
  • Arithmetic operators (e.g., "5*3").
  • Excel functions (e.g., "AVERAGE(1,2,3)").
  • Cell references (e.g., "A1", "Sheet2!B5"). Relative references are evaluated in the context of the worksheet object used.
  • Named ranges (e.g., "MyRange").
  • R1C1-style references are also supported if provided as strings (e.g., "R1C1").

Code Examples:
Here are practical examples using xlwings to demonstrate the Evaluate method:

  1. Evaluating a simple arithmetic expression:
import xlwings as xw
# Connect to the active workbook and sheet
wb = xw.books.active
sheet = wb.sheets['Sheet1']
# Evaluate 10 + 20
result = sheet.api.Evaluate("10+20")
print(result) # Output: 30
  1. Using an Excel function to calculate an average:
import xlwings as xw
wb = xw.books.active
sheet = wb.sheets[0]
# Assume cells A1:A5 contain numbers 1, 2, 3, 4, 5
# Evaluate the AVERAGE function on that range
avg_result = sheet.api.Evaluate("AVERAGE(A1:A5)")
print(avg_result) # Output: 3.0
  1. Referencing a cell and performing a calculation:
import xlwings as xw
wb = xlwings.Book('example.xlsx')
sheet = wb.sheets['Data']
# Suppose cell B2 contains the value 100 and C2 contains 0.2
# Calculate B2 * C2
computed = sheet.api.Evaluate("B2*C2")
print(computed) # Output: 20.0
  1. Evaluating a more complex formula with a named range:
import xlwings as xw
app = xw.App(visible=False)
wb = app.books.add()
sheet = wb.sheets[0]
# Define a named range for cells D1:D3
wb.api.Names.Add(Name="SalesData", RefersTo="=Sheet1!$D$1:$D$3")
# Assign values to D1:D3
sheet.range('D1').value = [200, 300, 400]
# Use SUM on the named range
total_sales = sheet.api.Evaluate("SUM(SalesData)")
print(total_sales) # Output: 900
wb.close()
app.quit()

How to use Worksheet.Delete in the xlwings API way

The Delete member of the Worksheet object in the Excel object model, accessible via the xlwings API in Python, provides a programmatic way to remove a specific worksheet from a workbook. This operation is irreversible through the API itself (akin to manually deleting a sheet and not saving the workbook), so it should be used with caution, especially on unsaved workbooks where data loss can occur.

Functionality
The primary function of the Delete method is to permanently delete the worksheet object on which it is called. After deletion, the worksheet is removed from the workbook’s Worksheets collection. If the deleted sheet was the only sheet in the workbook, xlwings and Excel will typically prevent its deletion to maintain at least one visible sheet, as an Excel workbook must contain at least one visible worksheet.

Syntax & Parameters
In xlwings, the method is called directly on a Sheet object (which represents a worksheet or chart sheet). The xlwings API abstracts the underlying COM calls into a simple Python method call.

sheet.delete()

There are no parameters for this method in the standard xlwings API. The action is applied to the sheet object referenced. It’s important to note that the Sheet object in xlwings corresponds to what the Excel Object Model calls a Worksheet (for standard worksheets) or a Chart object (for chart sheets). The delete() method works on both.

Code Examples

  1. Basic Deletion of a Specific Sheet:
    This example opens a workbook and deletes a sheet named “SheetToRemove”.
import xlwings as xw

# Open the workbook (use full path if needed)
wb = xw.Book("example.xlsx")

# Access the specific worksheet
sheet_to_delete = wb.sheets["SheetToRemove"]

# Delete the worksheet
sheet_to_delete.delete()

# Save the workbook to persist the change
wb.save()
wb.close()
  1. Deleting the Active Sheet:
    This example deletes whichever sheet is currently active in the open workbook.
import xlwings as xw

app = xw.App(visible=False) # Start Excel in the background
wb = app.books.open("data.xlsx")

# Delete the active sheet
wb.sheets.active.delete()

wb.save("data_modified.xlsx")
wb.close()
app.quit()
  1. Conditional Deletion Based on Content:
    A more practical example involves checking sheet names or content before deletion. This script deletes all sheets whose name contains the word “Temp”.
import xlwings as xw

wb = xw.Book("report.xlsx")

# Create a list of sheets to delete first to avoid iteration issues
sheets_to_delete = [sht for sht in wb.sheets if "Temp" in sht.name]

for sht in sheets_to_delete:
    print(f"Deleting sheet: {sht.name}")
    sht.delete()

wb.save()

How to use Worksheet.Copy in the xlwings API way

The Copy method of the Worksheet object in xlwings is a powerful tool for duplicating worksheets within or across workbooks. This functionality is essential for tasks such as creating templates, backing up data, or reorganizing workbook structures without manual copying and pasting. By leveraging the Excel object model through xlwings, users can automate these processes efficiently in Python.

In xlwings, the Copy method is accessed via the api property, which provides direct access to the underlying Excel object model. The syntax follows the pattern of the Excel VBA Copy method, where you specify the location for the copied sheet. The method signature is Copy(Before, After), with both parameters being optional. The Before parameter accepts a Worksheet object indicating the sheet before which the copy should be placed, while After specifies the sheet after which the copy should be inserted. If neither Before nor After is provided, Excel creates a new workbook to hold the copied worksheet. It’s important to note that you cannot use both Before and After simultaneously; specifying one excludes the other. These parameters allow precise control over the placement of the duplicated sheet within the workbook’s tab order.

For example, to copy a worksheet named “DataSheet” and place it before an existing sheet called “SummarySheet” in the same workbook, you can use the following xlwings code:

import xlwings as xw
wb = xw.Book("example.xlsx")
data_sheet = wb.sheets["DataSheet"]
summary_sheet = wb.sheets["SummarySheet"]
data_sheet.api.Copy(Before=summary_sheet.api)

This code snippet opens a workbook, references the “DataSheet” and “SummarySheet”, and copies “DataSheet” to appear directly before “SummarySheet”. The copied sheet will automatically be named “DataSheet (2)” by Excel to avoid naming conflicts.

Another common use case is copying a worksheet to a new workbook. By omitting both Before and After parameters, Excel generates a new workbook containing only the copied worksheet. For instance:

import xlwings as xw
wb = xw.Book("source.xlsx")
source_sheet = wb.sheets["SourceSheet"]
source_sheet.api.Copy()

After executing this, a new Excel workbook will open with a worksheet named “SourceSheet” that is a duplicate of the original. This is particularly useful for exporting specific sheets to separate files for distribution or analysis.

When copying between different workbooks, you need to reference the target workbook’s worksheets for the Before or After parameters. For example, to copy “Sheet1” from one workbook and place it after “SheetA” in another workbook:

import xlwings as xw
wb1 = xw.Book("workbook1.xlsx")
wb2 = xw.Book("workbook2.xlsx")
sheet1 = wb1.sheets["Sheet1"]
sheeta = wb2.sheets["SheetA"]
sheet1.api.Copy(After=sheeta.api)

How to use Worksheet.ClearCircles in the xlwings API way

The ClearCircles method of the Worksheet object in Excel is used to remove all circles that have been applied to cells via data validation error alert circles. These circles typically appear when data validation rules are violated, visually indicating invalid entries in a worksheet. The method is particularly useful for cleaning up the visual interface after data validation errors have been corrected or when preparing a sheet for presentation or further processing. It operates on the entire worksheet, affecting all cells within it.

In xlwings, the ClearCircles method can be accessed through a Worksheet object. The syntax is straightforward, as it does not require any parameters. The method is called directly on the worksheet instance.

Syntax:

worksheet.api.ClearCircles()

Here, worksheet is an xlwings Worksheet object representing the target sheet. The .api attribute provides access to the underlying Excel object model, allowing direct invocation of the native ClearCircles method. No arguments are needed, as the action applies to all circles from data validation errors on that specific worksheet.

Example:
Consider a scenario where a worksheet contains data validation rules, such as restricting input in column A to whole numbers between 1 and 10. If a user enters text like “abc” in cell A5, Excel may display a red circle around that cell (depending on error alert settings). To programmatically remove all such circles after reviewing and correcting the data, you can use the following xlwings code:

import xlwings as xw

# Connect to the active Excel instance or open a workbook
app = xw.App(visible=False) # Set to True if you want to see Excel
wb = app.books.open('example.xlsx')
sheet = wb.sheets['Sheet1']

# Assume data validation errors exist and circles are visible
# Clear all circles from data validation errors
sheet.api.ClearCircles()

# Save and close
wb.save()
wb.close()
app.quit()

How to use Worksheet.ClearArrows in the xlwings API way

The ClearArrows member of the Worksheet object in the Excel object model is accessible through the xlwings library, a powerful tool for automating Excel with Python. This method specifically targets the removal of tracer arrows within a worksheet. Tracer arrows are visual aids in Excel that help users understand formula dependencies and precedents by drawing arrows from cells that provide data to the cells that use that data (dependents) or from cells that are referenced by a formula (precedents). The ClearArrows method is essential for cleaning up the worksheet view, removing these arrows to declutter the interface, especially after auditing formulas or during the preparation of a final report.

In the xlwings API, the ClearArrows method is called directly on a Worksheet object. The syntax is straightforward, as the method does not require any parameters. It corresponds to the ClearArrows method in the Excel VBA object model, which clears all tracer arrows on the specified worksheet.

Syntax:

worksheet.api.ClearArrows()

Here, worksheet is an xlwings Worksheet object. The .api property provides direct access to the underlying Excel object model, allowing you to call native Excel methods like ClearArrows. This method clears all tracer arrows—both precedent and dependent arrows—from the active sheet. There are no parameters to specify, making its usage simple and direct.

Code Example:
The following xlwings code demonstrates how to use the ClearArrows method. It assumes you have an Excel workbook open and a specific worksheet selected.

import xlwings as xw

# Connect to the active Excel instance
app = xw.apps.active

# Specify the workbook (use the active workbook or open by name)
wb = app.books.active # or app.books['YourWorkbook.xlsx']

# Specify the worksheet by name or index
ws = wb.sheets['Sheet1'] # or wb.sheets[0]

# Clear all tracer arrows on the worksheet
ws.api.ClearArrows()

print("All tracer arrows have been cleared from the worksheet.")