Blog
How to use Worksheet.Hyperlinks in the xlwings API way
The Hyperlinks member of the Worksheet object in the Excel object model provides access to a collection of all hyperlinks on a specific worksheet. Through xlwings, this collection can be manipulated to add, modify, or retrieve hyperlinks programmatically, enabling dynamic linking to web pages, documents, email addresses, or other cells within the workbook. This functionality is essential for creating interactive and navigable Excel reports.
In xlwings, the Hyperlinks collection is accessed via the api property of a worksheet object. The syntax is ws.api.Hyperlinks, where ws is an xlwings Sheet object representing the worksheet. The Hyperlinks collection has several key methods, most notably Add. The Add method creates a new hyperlink and has the following parameters:
Anchor: A required parameter specifying the range where the hyperlink will be placed. This is typically aRangeobject.Address: The target address of the hyperlink (e.g., a URL like “https://www.example.com”).SubAddress: An optional parameter for linking to a specific location within a file, such as a named range or a cell reference (e.g., “Sheet2!A1”).ScreenTip: Optional text that appears when the user hovers over the hyperlink.TextToDisplay: The optional visible text for the hyperlink. If omitted, theAddressis displayed.
To retrieve an existing hyperlink, you can iterate through ws.api.Hyperlinks or access a specific one by index. Each hyperlink object in the collection has properties like Address, SubAddress, ScreenTip, and Range, which can be read or modified.
Below are practical xlwings code examples demonstrating the use of the Hyperlinks member:
import xlwings as xw
# Connect to an existing workbook and worksheet
wb = xw.Book('example.xlsx')
ws = wb.sheets['Sheet1']
# Example 1: Add a hyperlink to a website in cell A1
link_range = ws.range('A1')
ws.api.Hyperlinks.Add(Anchor=link_range.api,
Address='https://www.python.org',
ScreenTip='Visit Python Website',
TextToDisplay='Python.org')
# Example 2: Add a hyperlink to another cell in the same workbook
ws.api.Hyperlinks.Add(Anchor=ws.range('B2').api,
Address='',
SubAddress='Sheet2!C5',
TextToDisplay='Go to Sheet2')
# Example 3: Loop through all hyperlinks on the worksheet and print their addresses
for link in ws.api.Hyperlinks:
print(f"Hyperlink at {link.Range.Address}: {link.Address}")
# Example 4: Modify an existing hyperlink (e.g., the first one)
if ws.api.Hyperlinks.Count > 0:
first_link = ws.api.Hyperlinks(1) # Index is 1-based
first_link.Address = 'https://www.xlwings.org'
first_link.TextToDisplay = 'xlwings Docs'
# Save and close
wb.save()
wb.close()
How to use Worksheet.HPageBreaks in the xlwings API way
The HPageBreaks member of the Worksheet object in the Excel object model provides access to the collection of horizontal page breaks within a worksheet. In xlwings, this collection is accessible via the api property, which exposes the underlying Excel VBA object model. This allows for programmatic control over where pages break when the worksheet is printed, enabling precise formatting for reports and documents. The primary use is to add, delete, or query horizontal page breaks, which are essential for managing print layout in multi-page data sets.
Syntax and Parameters
In xlwings, you access the HPageBreaks collection through a worksheet object’s api property:
hpagebreaks = ws.api.HPageBreaks
The collection is 1-indexed, similar to Excel VBA. Key methods and properties include:
Add(Before): Adds a new horizontal page break.Before: A required parameter of typeObject. It specifies the range above which the page break will be inserted. You typically pass an xlwingsRangeobject’s.apiproperty (e.g.,ws.range("A10").api). The break is inserted above the top edge of this range.Count(Property): Returns aLongrepresenting the number of horizontal page breaks in the collection.Item(Index): Returns a singleHPageBreakobject from the collection.Index: The index number of the page break (1-indexed).Location(Property of anHPageBreakobject): Returns aRangeobject representing the cell where the page break is set (the cell immediately below the break line). This is read/write, allowing you to move an existing break.
Code Examples
- Adding a Horizontal Page Break:
Inserts a horizontal page break above row 15.
import xlwings as xw
wb = xw.Book("report.xlsx")
ws = wb.sheets["Sheet1"]
# Add a page break above cell A15
ws.api.HPageBreaks.Add(Before=ws.range("A15").api)
- Counting and Listing Page Breaks:
Prints the count and location of each horizontal page break.
import xlwings as xw
wb = xw.Book.active
ws = wb.sheets[0]
hbreaks = ws.api.HPageBreaks
print(f"Number of horizontal page breaks: {hbreaks.Count}")
for i in range(1, hbreaks.Count + 1):
break_obj = hbreaks.Item(i)
# The Location property returns the cell below the break
location_cell = break_obj.Location.Address
print(f" Break {i}: Above row {break_obj.Location.Row} (at {location_cell})")
- Deleting All Horizontal Page Breaks:
Clears all manually set horizontal page breaks from the sheet. Note: This does not remove automatic breaks inserted by Excel based on page margins and size.
import xlwings as xw
wb = xw.Book.active
ws = wb.sheets[0]
hbreaks = ws.api.HPageBreaks
# Loop backwards to avoid index shifting when deleting
for i in range(hbreaks.Count, 0, -1):
# The HPageBreak object itself doesn't have a .Delete() method.
# You delete it by clearing the break from its location.
hbreaks.Item(i).Location.PageBreak = -4142 # xlPageBreakNone
# Alternatively, reset all page breaks on the sheet:
# ws.api.ResetAllPageBreaks()
- Moving an Existing Page Break:
Changes the position of the first horizontal page break to be above row 25.
import xlwings as xw
wb = xw.Book.active
ws = wb.sheets[0]
hbreaks = ws.api.HPageBreaks
if hbreaks.Count >= 1:
first_break = hbreaks.Item(1)
first_break.Location = ws.range("A25").api
How to use Worksheet.FilterMode in the xlwings API way
The FilterMode property of a Worksheet object in the xlwings API is a read-only property that returns a Boolean value indicating whether the worksheet currently has any active autofilters applied. Specifically, it checks if the worksheet is in “filter mode,” meaning one or more columns have filter dropdowns enabled due to an autofilter being turned on. This is useful for programmatically determining the state of filters before performing operations like data processing or clearing filters, ensuring that your automation scripts can adapt dynamically to the worksheet’s condition.
Syntax and Parameters:
In xlwings, you access this property through a Sheet object (which corresponds to an Excel worksheet). The property does not take any arguments.
sheet.api.FilterMode
Here, sheet is an xlwings Sheet object. The .api attribute provides direct access to the underlying Excel object model (via COM on Windows or AppleScript on macOS), allowing you to use properties like FilterMode as defined in the Excel VBA documentation. The property returns True if the worksheet is in filter mode, and False otherwise.
Code Examples:
Below are practical examples of using the FilterMode property in xlwings:
- Checking Filter Mode State:
This example opens an Excel workbook, selects a specific sheet, and checks if filters are active.
import xlwings as xw
# Open the workbook and reference the sheet
wb = xw.Book("example.xlsx")
sheet = wb.sheets["Sheet1"]
# Check if the sheet is in filter mode
if sheet.api.FilterMode:
print("The worksheet has active autofilters.")
else:
print("No autofilters are currently applied.")
- Conditional Operations Based on Filter Mode:
This script usesFilterModeto decide whether to clear existing filters before applying new ones, preventing errors or unintended behavior.
import xlwings as xw
wb = xw.Book("data.xlsx")
sheet = wb.sheets[0]
# If filters are already on, clear them
if sheet.api.FilterMode:
sheet.api.AutoFilterMode = False # Turn off autofilter mode
print("Existing filters cleared.")
# Apply a new autofilter to a range (e.g., A1:D100)
sheet.range("A1:D100").api.AutoFilter(1)
print("New autofilter applied.")
- Monitoring Filter Changes:
In a more dynamic scenario, you might loop through multiple sheets to report their filter status.
import xlwings as xw
wb = xw.Book("report.xlsx")
for sheet in wb.sheets:
status = "Active" if sheet.api.FilterMode else "Inactive"
print(f"Sheet '{sheet.name}' has filters: {status}")
How to use Worksheet.EnableSelection in the xlwings API way
The Worksheet.EnableSelection property in the xlwings API provides control over the types of selections a user can make within a worksheet via the user interface. This property is particularly useful when you want to protect a worksheet but still allow users to interact with specific cells, such as unlocked cells in a form or template. By setting EnableSelection, you can restrict users from selecting locked cells, unlocked cells, or any cells at all, even when sheet protection is enabled. This enhances data integrity and user experience in shared or sensitive workbooks by preventing accidental modifications to critical data.
In xlwings, you access this property through the api property of a Worksheet object, which exposes the underlying Excel object model. The syntax for using EnableSelection is:worksheet.api.EnableSelection = value
Here, worksheet is an xlwings Worksheet object, and value is an integer that specifies the selection type. The possible values for value are defined in the Excel enumeration xlEnableSelection, which includes:
xlNoSelection(value: -4142): Prevents any selection in the worksheet.xlNoRestrictions(value: 0): Allows selection of all cells (default behavior when protection is off).xlUnlockedCells(value: 1): Permits selection only of unlocked cells.
To use these values in xlwings, you can import the constants from the win32com.client module if you are on Windows, or use their numeric equivalents directly for cross-platform compatibility. For example, xlUnlockedCells corresponds to the integer 1. This property is often set in conjunction with the Protect method to customize protection settings.
Below are code examples demonstrating the usage of Worksheet.EnableSelection with xlwings. Ensure you have an active workbook and worksheet object before running these snippets.
Example 1: Allow selection only of unlocked cells after protecting the worksheet. This is common in forms where users should only edit specific input fields.
import xlwings as xw
# Open an existing workbook or create a new one
wb = xw.Book('example.xlsx')
ws = wb.sheets['Sheet1']
# First, unlock some cells that users are allowed to edit (e.g., range A1:B2)
ws.range('A1:B2').api.Locked = False
# Protect the worksheet with a password (optional) and set EnableSelection
ws.api.Protect(Password='yourpassword', DrawingObjects=True, Contents=True, Scenarios=True)
ws.api.EnableSelection = 1 # xlUnlockedCells
# Now, users can only select and edit the unlocked cells A1:B2
Example 2: Disable all selections in a protected worksheet to make it completely read-only, preventing users from even clicking on cells.
import xlwings as xw
wb = xw.Book('example.xlsx')
ws = wb.sheets['Sheet1']
# Protect the worksheet without allowing any selections
ws.api.Protect(Password='secure123')
ws.api.EnableSelection = -4142 # xlNoSelection
# Users cannot select any cells, ensuring no accidental interactions
Example 3: Remove restrictions and allow full selection, which might be useful when temporarily disabling protection for editing.
import xlwings as xw
wb = xw.Book('example.xlsx')
ws = wb.sheets['Sheet1']
# If the worksheet is protected, unprotect it first
if ws.api.ProtectContents:
ws.api.Unprotect(Password='yourpassword')
# Set EnableSelection to allow all selections
ws.api.EnableSelection = 0 # xlNoRestrictions
# Users can now select any cell freely
How to use Worksheet.EnablePivotTable in the xlwings API way
The EnablePivotTable member of the Worksheet object in the Excel object model, accessible via xlwings, is a property that controls whether pivot tables can be manipulated or refreshed on a specific worksheet. This is particularly useful in scenarios where you need to lock down or protect the structure of pivot tables to prevent accidental changes by end-users, while still allowing the underlying data to be updated or other operations to proceed. By setting this property, developers can programmatically enable or disable pivot table interactions, enhancing the control over the workbook’s functionality during automated processes.
In xlwings, this corresponds to the api.EnablePivotTable property of a worksheet object. The property is a Boolean value, meaning it accepts True or False. When set to True, pivot tables on the worksheet are enabled for operations such as refreshing, sorting, or filtering. When set to False, these operations are disabled, effectively locking the pivot tables against modifications. This property is often used in conjunction with worksheet protection features to create a more secure and user-friendly Excel application.
Syntax:
In xlwings, you access this property through the worksheet’s underlying API object. The typical syntax is:
worksheet.api.EnablePivotTable = boolean_value
Here, worksheet is your xlwings Sheet object representing the target worksheet, and boolean_value is either True or False. To retrieve the current setting, you can simply read the property:
current_setting = worksheet.api.EnablePivotTable
This property does not take additional parameters. It directly reflects or sets the state for all pivot tables on that specific worksheet.
Example Usage:
Consider a scenario where you have an Excel report with a pivot table on a sheet named “SalesSummary”. You want to ensure that during an automated data refresh process, the pivot table is not accidentally altered by users or other macros. After refreshing the data source, you can disable the pivot table interactions, and then re-enable them only when specific administrative actions are required.
Below is an xlwings code example that demonstrates this:
import xlwings as xw
# Connect to the active workbook or open a specific one
wb = xw.Book('Report.xlsx')
# Access the specific worksheet
sales_sheet = wb.sheets['SalesSummary']
# Check the current EnablePivotTable setting
print(f"PivotTable enabled initially: {sales_sheet.api.EnablePivotTable}")
# Disable pivot table operations on this worksheet
sales_sheet.api.EnablePivotTable = False
print("PivotTable interactions are now disabled.")
# Perform other operations, like updating cell values or charts, without affecting pivot tables
sales_sheet.range('A1').value = 'Updated Report Title'
# Later, when needed, re-enable pivot table operations
sales_sheet.api.EnablePivotTable = True
print("PivotTable interactions have been re-enabled.")
# Optionally, refresh all pivot tables on the sheet to reflect any underlying data changes
for pivot in sales_sheet.api.PivotTables():
pivot.RefreshTable()
# Save and close
wb.save()
wb.close()
How to use Worksheet.EnableOutlining in the xlwings API way
EnableOutlining Property in xlwings
In Excel’s object model, the EnableOutlining property of a Worksheet object controls whether outlining (grouping and ungrouping of rows or columns) is allowed on the worksheet. When set to True, users can manually create and manipulate outlines via the Excel interface, such as grouping rows to collapse detail data and show summary rows. When set to False, outlining is disabled, preventing users from creating new groups or modifying existing ones. This property is useful for protecting the structure of a worksheet when distributing workbooks, ensuring that predefined outline levels remain intact.
Syntax in xlwings
In xlwings, the EnableOutlining property is accessed through the api property of a Sheet object (which corresponds to a Worksheet in Excel’s object model). The property is a boolean value.
sheet.api.EnableOutlining = True # Enable outlining
sheet.api.EnableOutlining = False # Disable outlining
- sheet: An xlwings
Sheetobject representing the worksheet. - .api: Provides direct access to the underlying Excel object model (via pywin32 on Windows or appscript on macOS).
- EnableOutlining: The property name as defined in the Excel object model. It can be set to
TrueorFalse.
Parameters and Usage
The property does not take additional parameters. It simply gets or sets a boolean value. Note that enabling or disabling outlining does not affect existing outlines; it only controls whether new outlines can be created or existing ones modified by the user. In Excel, this setting is often used in combination with worksheet protection (Protect method) to lock the outline structure.
Code Examples
- Enabling Outlining on a Worksheet
This example opens an Excel workbook, enables outlining on the first sheet, and saves the file. Users will then be able to group rows or columns manually in Excel.
import xlwings as xw
# Open an existing workbook or create a new one
app = xw.App(visible=False)
workbook = app.books.open('example.xlsx')
sheet = workbook.sheets[0]
# Enable outlining
sheet.api.EnableOutlining = True
# Save and close
workbook.save()
workbook.close()
app.quit()
- Disabling Outlining and Protecting the Worksheet
Here, outlining is disabled, and the worksheet is protected to prevent any changes to the outline structure. This is common in finalized reports.
import xlwings as xw
app = xw.App(visible=False)
workbook = app.books.open('report.xlsx')
sheet = workbook.sheets['Summary']
# Disable outlining to lock grouping features
sheet.api.EnableOutlining = False
# Protect the worksheet (optional: add a password)
sheet.api.Protect(Password="your_password", AllowFormattingCells=True)
workbook.save('report_locked.xlsx')
workbook.close()
app.quit()
- Checking the Current Outlining Status
You can also retrieve the current value ofEnableOutliningto conditionally modify the worksheet.
import xlwings as xw
app = xw.App(visible=False)
workbook = app.books.open('data.xlsx')
sheet = workbook.sheets[0]
# Get the current outlining status
is_outlining_enabled = sheet.api.EnableOutlining
print(f"Outlining is enabled: {is_outlining_enabled}")
# If disabled, enable it
if not is_outlining_enabled:
sheet.api.EnableOutlining = True
workbook.save()
workbook.close()
app.quit()
How to use Worksheet.EnableFormatConditionsCalculation in the xlwings API way
The EnableFormatConditionsCalculation member of the Worksheet object in Excel’s object model is a property that controls whether conditional formatting rules are recalculated automatically when worksheet data changes. When working with Excel via xlwings, this property is accessible and can be manipulated to optimize performance in workbooks with extensive or complex conditional formatting. By default, Excel recalculates conditional formats with each change to ensure visual accuracy, but this can slow down operations in large files. Disabling automatic recalculations allows for batch data updates without the overhead of repeated formatting evaluations, after which recalculations can be manually triggered or re-enabled.
In xlwings, this property is accessed through the api property of a worksheet object, which provides direct access to the underlying Excel VBA object model. The syntax for using it is straightforward: worksheet.api.EnableFormatConditionsCalculation. It is a Boolean property, meaning it accepts True or False values. Setting it to True (the default state) enables automatic calculation of conditional formats. Setting it to False disables these automatic calculations, which can be beneficial during macro execution or scripted data manipulation to speed up processing.
For example, consider a scenario where you are using a Python script with xlwings to update a large sales report worksheet that contains multiple conditional formatting rules highlighting top performers and outliers. If you update thousands of cells, having conditional formatting recalculate after each change would be inefficient. You can temporarily disable the calculations, perform all updates, and then re-enable it. Here is a code example:
import xlwings as xw
# Connect to the active workbook or open a specific one
wb = xw.Book.active
ws = wb.sheets['SalesData']
# Disable automatic conditional format calculation
ws.api.EnableFormatConditionsCalculation = False
# Perform bulk data updates
# For instance, update a range with new values
ws.range('A1:D1000').value = new_data_array # Assume new_data_array is a list of lists
# Re-enable automatic calculation
ws.api.EnableFormatConditionsCalculation = True
# Optionally, force a manual recalculation of conditional formats if needed
ws.api.Calculate
Another practical use is within a context manager to ensure the property is reset even if an error occurs during the update process. This approach enhances code robustness:
import xlwings as xw
wb = xw.Book('FinancialModel.xlsx')
ws = wb.sheets[0]
original_setting = ws.api.EnableFormatConditionsCalculation
try:
ws.api.EnableFormatConditionsCalculation = False
# Extensive data manipulation here
ws.range('B2:F500').formula = '=RAND()*100' # Example formula insertion
finally:
ws.api.EnableFormatConditionsCalculation = original_setting
wb.save()
How to use Worksheet.EnableCalculation in the xlwings API way
The EnableCalculation member of the Worksheet object in Excel’s object model is accessible through the xlwings library, enabling control over automatic formula calculation within a specific worksheet. This property is particularly useful for optimizing performance in workbooks with numerous or complex formulas. By temporarily disabling automatic calculation, you can perform multiple data updates or manipulations without triggering repeated recalculations, thereby speeding up macro execution. Once operations are complete, re-enabling calculation ensures all formulas are up-to-date.
Functionality:EnableCalculation is a Boolean property that determines whether Excel automatically recalculates formulas on the worksheet when cell values change. When set to False, Excel suspends automatic recalculation for that sheet, allowing manual control via Application.Calculate or similar methods. When set to True, the worksheet resumes normal automatic calculation behavior. This is especially beneficial in scenarios involving batch data processing or iterative operations where frequent recalculations would be inefficient.
Syntax in xlwings:
In xlwings, you access this property through a Worksheet object. The syntax is straightforward, as it maps directly to the Excel object model:
worksheet.api.EnableCalculation
Here, worksheet is an xlwings Sheet object representing the target worksheet. The property can be both read and assigned:
- To get the current setting:
current_setting = worksheet.api.EnableCalculation - To set the setting:
worksheet.api.EnableCalculation = Trueorworksheet.api.EnableCalculation = False
Parameters and Values:
The property accepts and returns Boolean values (True or False):
True: Enables automatic calculation for the worksheet (default state in Excel).False: Disables automatic calculation for the worksheet.
Note that this property is specific to each worksheet; changing it for one sheet does not affect others. For global calculation control, use app.api.Calculation on the Application object, but Worksheet.EnableCalculation provides finer-grained management.
Code Examples:
Below are practical xlwings API examples demonstrating the use of EnableCalculation:
- Disabling automatic calculation to optimize performance during data updates:
import xlwings as xw
# Connect to an existing workbook and select a worksheet
app = xw.App(visible=False)
wb = app.books.open('example.xlsx')
ws = wb.sheets['Sheet1']
# Disable automatic calculation
ws.api.EnableCalculation = False
# Perform multiple data operations (e.g., writing values)
for row in range(1, 101):
ws.range((row, 1)).value = row * 2 # Write values without triggering recalc
# Re-enable calculation and force a full recalculation
ws.api.EnableCalculation = True
ws.api.Calculate() # Manually recalculate the worksheet
# Save and close
wb.save()
wb.close()
app.quit()
- Checking and toggling the calculation setting based on current state:
import xlwings as xw
# Start with an active workbook
app = xw.App(visible=True)
wb = app.books.active
ws = wb.sheets[0]
# Get the current EnableCalculation setting
current_setting = ws.api.EnableCalculation
print(f"Current EnableCalculation setting: {current_setting}")
# Toggle the setting (enable if disabled, or vice versa)
ws.api.EnableCalculation = not current_setting
print(f"Updated EnableCalculation setting: {ws.api.EnableCalculation}")
# Example: If it was disabled, manually calculate a specific range
if not current_setting:
ws.range('A1:B10').api.Calculate() # Calculate only a specific range
# Keep the app open for demonstration
- Using EnableCalculation in a context manager-like pattern for safe operations:
import xlwings as xw
def batch_update_without_recalc(worksheet, data):
"""Helper function to update data without automatic calculation."""
original_setting = worksheet.api.EnableCalculation
try:
worksheet.api.EnableCalculation = False
# Perform data updates
for i, value in enumerate(data, start=1):
worksheet.range((i, 1)).value = value
finally:
worksheet.api.EnableCalculation = original_setting # Restore original setting
if original_setting:
worksheet.api.Calculate() # Recalculate if it was originally enabled
# Usage
app = xw.App(visible=False)
wb = app.books.add()
ws = wb.sheets[0]
data_list = [10, 20, 30, 40, 50]
batch_update_without_recalc(ws, data_list)
# Verify values
print(ws.range('A1:A5').value) # Output: [10.0, 20.0, 30.0, 40.0, 50.0]
wb.close()
app.quit()
How to use Worksheet.EnableAutoFilter in the xlwings API way
The EnableAutoFilter member of the Worksheet object in xlwings provides programmatic control over the AutoFilter functionality in Excel. This feature is essential for automating data analysis tasks, allowing developers to dynamically show or hide rows based on specific criteria without manual intervention. When enabled, AutoFilter adds drop-down arrows to the header row of a data range, facilitating quick filtering operations. In xlwings, this property can be both read and set, enabling scripts to check the current filter state or to ensure a filter is applied before performing operations like data extraction or formatting.
The syntax for accessing the EnableAutoFilter property in xlwings is straightforward, as it maps directly to the Excel Object Model. It is accessed through a Worksheet object instance. The property is a Boolean value, meaning it can be set to True to enable AutoFilter or False to disable it. When reading the property, it returns True if AutoFilter is currently active on the worksheet and False otherwise. There are no parameters for this property. The basic usage pattern is:
worksheet.api.EnableAutoFilter = True # To enable the AutoFilter
current_state = worksheet.api.EnableAutoFilter # To read the current state
It is important to note that enabling AutoFilter via this property typically applies it to the current used range of the worksheet. For more precise control, such as specifying the exact range to filter, one would use the Range.autofilter() method instead. The EnableAutoFilter property serves as a master switch for the feature on a given sheet.
Here are practical code examples demonstrating the use of the EnableAutoFilter property with xlwings:
Example 1: Enabling AutoFilter on a Worksheet
This script opens an Excel workbook and enables AutoFilter on the first worksheet. This is useful for preparing a sheet for interactive or subsequent programmatic filtering.
import xlwings as xw
# Connect to an open workbook or open a new one
wb = xw.Book('data_analysis.xlsx')
sheet = wb.sheets['SalesData']
# Enable AutoFilter for the worksheet
sheet.api.EnableAutoFilter = True
# Save the workbook to persist the change
wb.save()
Example 2: Checking and Toggling AutoFilter State
This example checks if AutoFilter is enabled on a specific worksheet. If it is not, the script enables it. This pattern ensures the filter is active before performing operations that depend on it, such as reading visible cells only.
import xlwings as xw
app = xw.App(visible=False)
wb = app.books.open('monthly_report.xlsx')
sheet = wb.sheets[0]
# Check the current AutoFilter state
if not sheet.api.EnableAutoFilter:
print("AutoFilter is disabled. Enabling it now.")
sheet.api.EnableAutoFilter = True
else:
print("AutoFilter is already enabled.")
# Perform an operation, like getting only visible rows from a filtered range
# (Assuming data starts in A1 and filters are applied)
visible_range = sheet.used_range.current_region # Gets the contiguous data range
# ... further processing on visible_range
wb.save()
wb.close()
app.quit()
Example 3: Disabling AutoFilter
After automated data processing, you might want to clean up the worksheet by removing the filter dropdowns for a cleaner presentation or to prevent accidental user filtering.
import xlwings as xw
with xw.App(visible=False) as app:
wb = app.books.open('processed_data.xlsx')
sheet = wb.sheets['Final']
# Disable AutoFilter if it is active
if sheet.api.EnableAutoFilter:
sheet.api.EnableAutoFilter = False
print("AutoFilter has been disabled.")
wb.save()
How to use Worksheet.DisplayRightToLeft in the xlwings API way
The DisplayRightToLeft property of a Worksheet object in Excel is a Boolean property that controls the reading order and layout direction of the worksheet. When set to True, the worksheet is displayed in a right-to-left orientation, which is particularly useful for languages that are written from right to left, such as Arabic, Hebrew, or Farsi. This setting affects the alignment of text, the order of columns (with column A appearing on the right side), and the direction of scrolling. When set to False (the default), the worksheet uses the standard left-to-right orientation. In xlwings, this property can be accessed and modified directly through the api property of a Worksheet object, which provides access to the underlying Excel object model.
Syntax in xlwings:
The property is accessed via the api property of a Worksheet object. The syntax is:
worksheet.api.DisplayRightToLeft
This property is both readable and writable. It accepts and returns a Boolean value:
- True: Enables right-to-left display.
- False: Disables right-to-left display (left-to-right default).
Parameters:
This property does not take any parameters. It is a simple Boolean attribute.
Example Usage:
Below are xlwings code examples demonstrating how to get and set the DisplayRightToLeft property.
- Getting the current DisplayRightToLeft setting:
import xlwings as xw
# Open an existing workbook or create a new one
wb = xw.Book('example.xlsx')
sheet = wb.sheets['Sheet1']
# Get the current DisplayRightToLeft value
current_setting = sheet.api.DisplayRightToLeft
print(f"Current DisplayRightToLeft setting: {current_setting}")
- Setting DisplayRightToLeft to True (right-to-left orientation):
import xlwings as xw
# Open an existing workbook
wb = xw.Book('example.xlsx')
sheet = wb.sheets['Sheet1']
# Set the worksheet to display right-to-left
sheet.api.DisplayRightToLeft = True
print("Worksheet is now set to right-to-left display.")
- Toggling the DisplayRightToLeft setting:
import xlwings as xw
# Open an existing workbook
wb = xw.Book('example.xlsx')
sheet = wb.sheets['Sheet1']
# Toggle the current setting
sheet.api.DisplayRightToLeft = not sheet.api.DisplayRightToLeft
new_setting = sheet.api.DisplayRightToLeft
print(f"Toggled DisplayRightToLeft to: {new_setting}")
- Applying DisplayRightToLeft to multiple worksheets:
import xlwings as xw
# Open an existing workbook
wb = xw.Book('example.xlsx')
# Loop through all worksheets and set them to right-to-left display
for sheet in wb.sheets:
sheet.api.DisplayRightToLeft = True
print(f"Set {sheet.name} to right-to-left display.")