Archive

How to use Worksheet.Creator in the xlwings API way

The Creator property of a Worksheet object in the Excel object model is a read-only property that returns a 32-bit integer representing the application in which the worksheet was originally created. This is particularly useful for compatibility and identification purposes when working with files that may have been created in different versions of Excel or other spreadsheet applications. In xlwings, you can access this property to determine the creator application of a specific worksheet.

Functionality:
The primary function of the Creator property is to identify the application that created the worksheet. This can be important in scenarios where macros or specific features depend on the original application version. For example, it helps in ensuring backward compatibility or in logging the origin of spreadsheet files during automated processing.

Syntax in xlwings:
In xlwings, the Creator property is accessed through the api property of a worksheet object, which provides direct access to the underlying Excel object model. The syntax is straightforward:

worksheet.api.Creator

This returns an integer value (a long integer) that corresponds to the creator application. Common values include:

  • 1480803660 for Microsoft Excel (this is a typical value for Excel, but it can vary based on version and system).
  • Other values may represent different applications like older versions or third-party tools.

Parameters:
The Creator property does not accept any parameters; it is a simple property getter.

Example Usage:
Here is a practical example of how to use the Creator property in xlwings to check the creator of a worksheet in an Excel workbook:

import xlwings as xw

# Open an existing workbook
wb = xw.Book('example.xlsx')

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

# Retrieve the Creator property
creator_code = ws.api.Creator

# Display the result
print(f"The creator code of the worksheet is: {creator_code}")

# Optionally, interpret the code (this is a simplified example)
if creator_code == 1480803660:
    print("This worksheet was created in Microsoft Excel.")
else:
    print("This worksheet may have been created in a different application.")

# Close the workbook if needed
wb.close()

How to use Worksheet.ConsolidationSources in the xlwings API way

The ConsolidationSources property of the Worksheet object in Excel returns an array of strings that represent the source data ranges for a consolidation on the specified worksheet. This is particularly useful when you have a worksheet that consolidates data from multiple other worksheets or ranges, and you need to programmatically inspect or manage these sources. In xlwings, you can access this property to retrieve this information, enabling automation in scenarios where consolidation settings need to be reviewed or dynamically adjusted.

Functionality:
This property allows you to get the references (as text strings) of all the ranges that are included in a consolidation on the worksheet. It is a read-only property. Each string in the returned array typically follows Excel’s reference style, such as "[WorkbookName]SheetName!Range". This can be used for auditing, logging, or further processing where the consolidation structure is relevant.

Syntax in xlwings:
In xlwings, you access this property via the api property of a Worksheet object, which exposes the underlying Excel object model. The syntax is:

sources = worksheet.api.ConsolidationSources
  • worksheet: This is your xlwings Worksheet object.
  • .api: This provides access to the native Excel VBA object model.
  • .ConsolidationSources: This property returns a Variant array (in Python, it’s typically converted to a tuple or list of strings). If there is no consolidation on the worksheet, it returns None or an empty array.

The property does not take any parameters. The returned array contains each source as a string. The strings represent the references in the format used by Excel (e.g., R1C1 or A1 style, depending on the application’s reference style setting).

Example:
Suppose you have an Excel workbook named “ConsolidatedData.xlsx” with a worksheet named “Summary”. This “Summary” sheet consolidates data from two other sheets: “Data1” and “Data2”, with ranges “A1:C10” on each. You can use xlwings to retrieve these consolidation sources.

import xlwings as xw

# Open the workbook and select the worksheet
wb = xw.Book("ConsolidatedData.xlsx")
summary_sheet = wb.sheets["Summary"]

# Get the consolidation sources
sources = summary_sheet.api.ConsolidationSources

# Check if there are any sources and print them
if sources:
    print("Consolidation Sources:")
    for source in sources:
        print(f" - {source}")
else:
    print("No consolidation sources found on this worksheet.")

# Close the workbook if needed
wb.close()

How to use Worksheet.ConsolidationOptions in the xlwings API way

The ConsolidationOptions member of a Worksheet object in Excel’s object model refers to settings that control how data consolidation is performed on the worksheet. In xlwings, this is accessed through the api property, which provides direct access to the underlying Excel object model. The ConsolidationOptions property returns a Consolidation object, which itself has several properties and methods to define the source ranges, function, and other options for consolidating data from multiple ranges into a single summary range. This feature is useful for summarizing data from various sheets or workbooks, such as combining sales figures from different regions.

Syntax and Parameters:
In xlwings, you access ConsolidationOptions via Worksheet.api.ConsolidationOptions. This returns a Consolidation object with key properties including:

  • Sources: A list of source ranges as strings (e.g., ["Sheet1!R1C1:R10C5", "Sheet2!R1C1:R10C5"]). Each string represents a range in R1C1-style notation.
  • Function: An Excel constant specifying the consolidation function, such as xlwings.constants.xlSum for sum or xlwings.constants.xlAverage for average. Common values include:
  • xlSum (-4157): Adds values.
  • xlAverage (-4106): Calculates the average.
  • xlCount (-4112): Counts non-empty cells.
  • xlMax (-4136): Finds the maximum value.
  • xlMin (-4139): Finds the minimum value.
  • TopRow and LeftColumn: Boolean values indicating whether to use labels from the top row or left column of the source ranges for consolidation.
  • CreateLinks: A boolean that, if True, creates links to the source data (default is False).

To set up consolidation, you typically assign these properties and then use the Consolidate method of the Range object where you want the consolidated data. However, note that ConsolidationOptions itself is primarily for retrieving or setting options rather than executing consolidation directly.

Code Example:
Here is an example using xlwings to set consolidation options and perform consolidation on a worksheet. This script assumes you have an Excel workbook open with data in multiple sheets, and you want to sum values from specific ranges into a summary sheet.

import xlwings as xw

# Connect to the active workbook
wb = xw.books.active
# Assume we have a summary sheet named "Summary"
summary_sheet = wb.sheets["Summary"]

# Access the ConsolidationOptions via the api property
consolidation = summary_sheet.api.ConsolidationOptions

# Set the sources for consolidation (using R1C1 notation for ranges from two sheets)
consolidation.Sources = ["Sheet1!R1C1:R10C3", "Sheet2!R1C1:R10C3"]

# Set the function to sum (xlSum constant)
consolidation.Function = xw.constants.xlSum

# Use labels from the top row and left column
consolidation.TopRow = True
consolidation.LeftColumn = True
# Do not create links to source data
consolidation.CreateLinks = False

# Now, consolidate the data into a starting cell on the summary sheet (e.g., A1)
# The Consolidate method is called on the Range object where consolidation begins
summary_sheet.range("A1").api.Consolidate(Sources=consolidation.Sources,
Function=consolidation.Function,
TopRow=consolidation.TopRow,
LeftColumn=consolidation.LeftColumn,
CreateLinks=consolidation.CreateLinks)

# Optionally, you can check the current consolidation settings
print("Current sources:", consolidation.Sources)
print("Function used:", consolidation.Function)

How to use Worksheet.ConsolidationFunction in the xlwings API way

The ConsolidationFunction property of the Worksheet object in Excel VBA refers to the function used when consolidating ranges (e.g., Sum, Count, Average). However, in the context of xlwings, a Python library for automating Excel, direct access to this specific VBA property is not typically exposed as a first-class API feature because xlwings focuses more on data manipulation, calculation, and automation rather than replicating the entire UI-driven consolidation feature set. The consolidation functionality in Excel is often accessed via the UI (Data > Consolidate) or VBA, and xlwings can automate these actions through the .api property to access the underlying Excel object model.

In xlwings, to utilize the ConsolidationFunction, you would work through the Excel Object Model via the api property. The ConsolidationFunction is a property of a Worksheet object in Excel’s VBA, which returns or sets the function used for consolidation (an XlConsolidationFunction constant). It is primarily used when a worksheet has a consolidation set up. The syntax in VBA is Worksheet.ConsolidationFunction, and in xlwings, you access it similarly through the worksheet’s API object.

Functionality:
This property indicates the consolidation function (e.g., sum, average, count) applied to data ranges that have been consolidated on the worksheet. It is read-only and returns an integer corresponding to an XlConsolidationFunction enumeration. Common values include:

  • -4106 or xlSum for summation
  • -4109 or xlCount for counting numbers
  • -4116 or xlAverage for averaging
  • -4135 or xlMax for maximum value
  • -4136 or xlMin for minimum value
    It is useful for programmatically checking the type of consolidation applied, especially in automated reports or when auditing workbook structures.

Syntax in xlwings:
To access this property in xlwings, use:

worksheet.api.ConsolidationFunction

This returns an integer representing the consolidation function constant. Note that this property is only meaningful if the worksheet contains a consolidation range; otherwise, it may return xlNone or another default.

Example Usage:
Suppose you have an Excel workbook with a worksheet that has a consolidation set up to sum data from multiple ranges. You can use xlwings to inspect the consolidation function:

import xlwings as xw

# Connect to the active workbook or open a specific one
wb = xw.Book('consolidation_example.xlsx')
ws = wb.sheets['ConsolidatedSheet']

# Access the ConsolidationFunction property via .api
consolidation_func = ws.api.ConsolidationFunction

# Map the integer to a readable function name
func_map = {
-4106: 'Sum',
-4109: 'Count',
-4116: 'Average',
-4135: 'Max',
-4136: 'Min',
-4142: 'Unknown' # xlNone or other
}
func_name = func_map.get(consolidation_func, 'Not Consolidated')

print(f"The consolidation function on '{ws.name}' is: {func_name} (Code: {consolidation_func})")

# Optionally, you can set up a new consolidation using VBA methods via .api
# This requires using the Range.Consolidate method, which is more complex
# Example: Consolidate data from multiple ranges with a sum function
if func_name == 'Not Consolidated':
    # Define source ranges (example: ranges from other sheets)
    sources = ["Sheet1!R1C1:R10C5", "Sheet2!R1C1:R10C5"]
    ws.api.Range("A1").Consolidate(Sources=sources, Function=-4106) # -4106 for xlSum
    print("Consolidation set up with Sum function.")
else:
    print("Consolidation already exists.")

wb.save()
wb.close()

How to use Worksheet.CommentsThreaded in the xlwings API way

The Worksheet object’s CommentsThreaded property in xlwings provides access to the collection of threaded comments associated with a specific worksheet. Threaded comments, introduced in newer versions of Microsoft Excel, allow for modern, conversation-style discussions attached to a cell, differing from the older single “Comment” (now often called a “Note”). This property is essential for programmatically managing these collaborative discussions, enabling developers to read, add, reply to, or delete comment threads directly from Python, thereby automating feedback collection, review processes, or annotation systems within workbooks.

Syntax and Key Members

The property is accessed via Worksheet.comments_threaded. It returns a CommentsThreaded collection object. The primary method for adding a new threaded comment is add. The key syntax in xlwings is:

my_comment = ws.comments_threaded.add(cell, text, author=None)
  • cell (required): An xlwings Range object or a string address (e.g., "A1") specifying the cell to which the comment thread will be attached.
  • text (required): A string containing the content of the initial comment in the thread.
  • author (optional): A string specifying the author’s name for the comment. If omitted, it typically defaults to a system or application-defined name.

The add method returns a CommentThreaded object, which itself has useful properties and methods, such as:

  • .text: Gets or sets the text of the specific comment (if accessed from a reply within the thread, careful indexing of the .comments collection is needed).
  • .replies: A collection of replies within the thread. You can use .replies.add(text) to post a new reply.
  • .delete(): Deletes the entire comment thread.

Code Examples

  1. Adding a New Threaded Comment:
    This example adds a new threaded comment to cell B5.
import xlwings as xw
wb = xw.Book("example.xlsx")
ws = wb.sheets["Sheet1"]
new_thread = ws.comments_threaded.add("B5", "Initial review: Please verify these figures.", author="AnalysisBot")
wb.save()
  1. Reading Existing Threaded Comments:
    This loop iterates through all threaded comments on the sheet and prints their location and the text of the first comment in each thread.
import xlwings as xw
wb = xw.Book("example.xlsx")
ws = wb.sheets["Sheet1"]
for comment_thread in ws.comments_threaded:
    # The CommentThreaded object's .cell property gives its location
    print(f"Cell {comment_thread.cell.address}: {comment_thread.text}")
  1. Replying to a Comment Thread:
    This example finds a comment thread in cell D10 and adds a reply to it.
import xlwings as xw
wb = xw.Book("example.xlsx")
ws = wb.sheets["Sheet1"]
# Assuming a thread exists in D10. In practice, you might loop to find it.
for thread in ws.comments_threaded:
    if thread.cell.address == "$D$10":
        thread.replies.add("Reply: Figures have been updated and confirmed.", author="ReviewerJane")
        break
wb.save()
  1. Deleting a Specific Comment Thread:
    This deletes the threaded comment located at cell F7.
import xlwings as xw
wb = xw.Book("example.xlsx")
ws = wb.sheets["Sheet1"]
for thread in ws.comments_threaded:
    if thread.cell.address == "$F$7":
        thread.delete()
        break
wb.save()

How to use Worksheet.Comments in the xlwings API way

The Worksheet.Comments property in xlwings provides access to the collection of all comments (also known as notes in newer Excel versions) within a specific worksheet. This property is essential for programmatically managing cell annotations, enabling developers to add, retrieve, modify, or delete comments. Comments are useful for adding explanatory notes, instructions, or feedback directly to cells, enhancing the interactivity and clarity of Excel workbooks. Through xlwings, you can automate comment-related tasks, such as bulk updates or extracting comment text for reporting purposes.

The syntax for accessing comments via xlwings is straightforward. The property returns a Comments object that represents a collection of individual Comment objects. You can reference it as: sheet.comments, where sheet is an xlwings Worksheet object. To interact with a specific comment, you can index it by its cell address or use iteration over all comments. Key methods and properties include:

  • add(cell, text): Adds a new comment to a specified cell with the given text. The cell parameter can be a string (e.g., “A1”) or a tuple (e.g., (1, 1)), and text is a string containing the comment content.
  • count: Returns the number of comments in the worksheet.
  • item(index): Retrieves a Comment object by index (0-based) or by cell address.
  • clear(): Removes all comments from the worksheet.
    Each Comment object has properties like text (to get or set the comment text), author (to get or set the author name), and delete() (to remove the comment). Note that in Excel, comments and notes are distinct; xlwings primarily handles traditional comments, but it may adapt based on the Excel version.

For example, consider a scenario where you need to add a comment to cell B5 with a reminder and then list all comments in the worksheet. Here is a code instance using xlwings:

import xlwings as xw

# Open an existing workbook and select a worksheet
wb = xw.Book('example.xlsx')
sheet = wb.sheets['Sheet1']

# Add a new comment to cell B5
sheet.comments.add('B5', 'Review this value for accuracy.')

# Get the count of comments
comment_count = sheet.comments.count
print(f"Total comments: {comment_count}")

# Iterate through all comments and print their details
for comment in sheet.comments:
    print(f"Cell: {comment.cell.address}, Text: {comment.text}, Author: {comment.author}")

# Modify an existing comment in cell A3 (if it exists)
if sheet.comments.count > 0:
    # Assuming A3 has a comment; you can check with try-except or conditions
    try:
        comment_a3 = sheet.comments['A3']
        comment_a3.text = 'Updated note: Please verify.'
    except Exception as e:
        print(f"Comment not found in A3: {e}")

# Delete a comment from cell B5
sheet.comments['B5'].delete()

# Clear all comments from the worksheet
sheet.comments.clear()

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

How to use Worksheet.Columns in the xlwings API way

The Columns property of the Worksheet object in xlwings provides a way to access and manipulate entire columns within a specific worksheet. It is a powerful feature for performing operations on columnar data, such as formatting, resizing, or extracting values, without needing to iterate through individual cells. This property returns a Range object that represents one or more columns, enabling batch operations that enhance code efficiency and readability.

In xlwings, the syntax for accessing columns is straightforward. You can reference columns using the Columns property on a Sheet object (which is accessed via the workbook’s sheets collection). The basic syntax is: sheet.columns[item]. Here, item can be specified in several ways:

  • A single integer (e.g., 1 for column A, 2 for column B).
  • A string representing the column letter (e.g., 'A' for column A).
  • A slice to select multiple columns (e.g., 'A:C' or 1:3 for columns A through C).
  • A list or tuple for non-contiguous columns (e.g., [1, 3, 5] or ['A', 'C', 'E']).
    When using this property, it’s important to note that xlwings uses 1-based indexing for columns, aligning with Excel’s convention. The returned Range object can then be used to apply various methods and properties, such as setting values, adjusting width, or changing formatting.

For example, to set the width of column B to 20 points in a worksheet named “DataSheet”, you can use: sheet.columns['B'].column_width = 20. This directly accesses column B and modifies its width. Similarly, to clear the contents of columns D through F, you can write: sheet.columns['D:F'].clear_contents(). This demonstrates how the Columns property simplifies tasks that would otherwise require loops or more complex range specifications.

Here are a few practical code examples using the Columns property in xlwings:

  1. Setting values for an entire column: To populate column A with a list of values, you can assign a list directly. For instance, sheet.columns['A'].value = [['Item1'], ['Item2'], ['Item3']] will fill cells A1, A2, and A3 with the specified items. Note that values should be provided as a list of lists, where each sublist corresponds to a row in the column.
  2. Formatting multiple columns: To apply a bold font to columns C and E, you can use: sheet.columns[['C', 'E']].api.Font.Bold = True. This leverages the underlying Excel API via the .api attribute for advanced formatting, showcasing xlwings’ flexibility in combining high-level and low-level operations.
  3. Autofitting column widths based on content: To automatically adjust the width of all columns in a worksheet to fit their content, you can use: sheet.columns.autofit(). This method resizes each column so that the longest entry is fully visible, improving readability without manual adjustments.
  4. Hiding specific columns: If you need to hide columns B and D, you can execute: sheet.columns[['B', 'D']].hidden = True. This property controls the visibility of columns, useful for focusing on relevant data in reports or dashboards.

How to use Worksheet.CodeName in the xlwings API way

The CodeName property of a Worksheet object in Excel is a powerful feature that allows developers to assign a unique, programmatic identifier to a sheet. Unlike the Name property, which is the visible tab name a user can change, the CodeName is intended to remain static through the life of the workbook. This makes it an ideal reference in VBA macros and, by extension, in xlwings scripts, as it provides a stable way to target a specific sheet even if a user renames its tab. In xlwings, you access this property directly through the api object, which grants raw access to the underlying Excel object model.

The syntax for accessing the CodeName property in xlwings is straightforward. Since it is a read-only property in the context of xlwings (typically set in the Excel VBA IDE), you primarily retrieve its value. The call format is:

sheet.api.CodeName

Here, sheet is an xlwings Sheet object. The property returns a string representing the sheet’s programmatic name. It’s important to note that while you can read the CodeName via xlwings, changing it programmatically is not directly supported through the standard xlwings API; it is generally set in the Visual Basic for Applications editor (by changing the (Name) property in the Properties window for the sheet) before or during development.

Consider a workbook where you have a data input sheet. In the VBA IDE, you set its CodeName to shDataInput. Even if a user later changes the tab name from “Data” to “Monthly Data”, your xlwings code can still reliably find it. Here is a practical example:

import xlwings as xw

# Connect to the active workbook
wb = xw.books.active

# Method 1: Get a sheet by its CodeName by iterating
target_code_name = "shDataInput"
target_sheet = None
for sheet in wb.sheets:
    if sheet.api.CodeName == target_code_name:
        target_sheet = sheet
        break

if target_sheet:
    print(f"Found sheet with CodeName: {target_sheet.api.CodeName}")
    # Now you can work with the sheet reliably
    target_sheet.range("A1").value = "Updated via CodeName"
else:
    print("Sheet not found.")

# Method 2: A more direct approach using the `api` collection (requires knowing the index/name in the VBA project)
# This is less common but demonstrates the direct COM access.
try:
    # The VBA workbook object has a `Worksheets` collection accessible via `api`
    vba_sheet = wb.api.Worksheets(target_code_name) # This uses the *CodeName* in    the VBA collection
    xw_sheet = xw.Sheet(vba_sheet)
    print(f"Direct access successful. Sheet name (tab): {xw_sheet.name}")
except Exception as e:
    print(f"Direct access failed: {e}")

How to use Worksheet.CircularReference in the xlwings API way

In Excel, a circular reference occurs when a formula refers back to its own cell, either directly or through a chain of references, which can lead to calculation errors or iterative calculations. The CircularReference member of a Worksheet object in the xlwings API is a property that allows developers to identify and manage such references programmatically. This is particularly useful for debugging complex spreadsheets, ensuring data integrity, and automating error-checking processes. By accessing this property, users can pinpoint cells that contain circular formulas, enabling them to correct or analyze these references efficiently within Python scripts.

The CircularReference property is part of the Worksheet object in xlwings and provides read-only access to the range representing the first circular reference found on the worksheet. If no circular reference exists, it returns None. The syntax for accessing this property in xlwings is straightforward, as it does not require any parameters. It leverages the underlying Excel object model through the xlwings wrapper, making it seamless to integrate into Python code for Excel automation.

Syntax:
worksheet.api.CircularReference
Here, worksheet is an instance of the xlwings Sheet object (which corresponds to the Excel Worksheet). The .api attribute exposes the native Excel object model, allowing access to the CircularReference property. This property returns a Range object representing the cell with the circular reference, or None if there are none. Note that this property is specific to the Excel API and is accessed via xlwings’ COM or Apple Script bridge, depending on the operating system.

Example Use Cases:
To demonstrate the usage, consider an Excel workbook where a worksheet contains formulas that might create circular references. In xlwings, you can open the workbook, check for circular references, and take action based on the findings. Below is a code example that illustrates this:

import xlwings as xw

# Open an existing workbook and specify a worksheet
wb = xw.Book('example.xlsx')
ws = wb.sheets['Sheet1']

# Access the CircularReference property
circ_ref = ws.api.CircularReference

# Check if a circular reference exists
if circ_ref is not None:
    print(f"Circular reference found at: {circ_ref.address}")
    # You can get details like the cell value or formula
    print(f"Cell formula: {circ_ref.formula}")
    print(f"Cell value: {circ_ref.value}")

    # Optionally, clear or modify the circular reference
    # For example, set the cell to a static value or adjust the formula
circ_ref.value = 0 # Resetting to zero as a simple fix
    print("Circular reference has been addressed.")
else:
    print("No circular references detected in this worksheet.")

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

How to use Worksheet.Cells in the xlwings API way

The Cells property of a Worksheet object in the Excel object model is a fundamental member for accessing and manipulating individual cells or ranges of cells within a worksheet. In xlwings, this is accessed through the api property, which provides direct access to the underlying Excel object model, allowing for precise control similar to VBA. The Cells property is versatile, enabling both reading and writing of cell values, as well as formatting and other cell-specific operations.

Functionality:
The primary function of the Cells property is to return a Range object that represents a single cell or a collection of cells. It is commonly used to refer to cells by their row and column numbers, which is particularly useful in loops or when programmatically determining cell positions. This property is essential for tasks that require iterating over cells, dynamically referencing ranges, or accessing cells based on calculated indices.

Syntax:
In xlwings, the syntax to access the Cells property is:

worksheet.api.Cells(row_index, column_index)
  • row_index: Required. An integer that specifies the row number of the cell (1-indexed).
  • column_index: Required. An integer that specifies the column number of the cell (1-indexed). Alternatively, a string representing the column letter (e.g., “A”) can be used, but when using the Cells property directly via api, it typically expects numeric indices for consistency with the Excel object model.

The Cells property can also be called with a single argument to return a range encompassing all cells in the worksheet, though this is less common. For example, worksheet.api.Cells without arguments refers to all cells, but in practice, worksheet.used_range or similar methods are often preferred for performance.

Examples:
Here are several xlwings API code examples demonstrating the use of the Cells property:

  1. Accessing a Single Cell Value:
import xlwings as xw
wb = xw.Book('example.xlsx')
ws = wb.sheets['Sheet1']
# Get value from cell at row 5, column 3 (C5)
cell_value = ws.api.Cells(5, 3).Value
print(cell_value)
# Set value in cell at row 2, column 1 (A2)
ws.api.Cells(2, 1).Value = "Hello, World!"
  1. Iterating Over a Range of Cells:
# Write values to the first 5 rows in column A
for i in range(1, 6):
    ws.api.Cells(i, 1).Value = f"Data {i}"
# Read values from the first 3 rows in column B
for i in range(1, 4):
    print(ws.api.Cells(i, 2).Value)
  1. Formatting Cells:
# Change the font color of cell D10 to red
ws.api.Cells(10, 4).Font.Color = 0xFF0000 # RGB color for red
# Set the interior color of cell E5 to yellow
ws.api.Cells(5, 5).Interior.Color = 0xFFFF00
  1. Using Cells with Variables for Dynamic References:
row_num = 7
col_num = 4
# Dynamically access cell at row 7, column 4 (D7)
dynamic_cell = ws.api.Cells(row_num, col_num)
dynamic_cell.Value = "Dynamic Entry"
  1. Accessing All Cells (Entire Worksheet):
# Refer to all cells in the worksheet (use with caution for large sheets)
all_cells = ws.api.Cells
print(f"Total rows: {all_cells.Rows.Count}, Total columns: {all_cells.Columns.Count}")