How to use Workbook.Item in the xlwings API way

The Item member of the Workbook object in the Excel object model is a property that provides access to individual worksheets or charts within a workbook by their index number or name. In xlwings, this functionality is not exposed through an explicit Item property as in VBA, but is instead accessed directly through the workbook’s indexing or via methods like .sheets[]. This design offers a more Pythonic and intuitive way to retrieve specific sheets, aligning with common Python container behaviors.

Functionality
The primary function is to return a single Sheet object (which can be a Worksheet or Chart object) from the Sheets collection of a workbook. This allows for targeted operations on a specific sheet, such as reading data, writing values, or formatting cells, without needing to activate or select it first.

Syntax & Parameters
In xlwings, you access a sheet by its index or name using the sheets property of a Book object (xlwings’ equivalent of a Workbook). The syntax is:

sheet = wb.sheets[index_or_name]
  • wb: The xlwings Book object instance.
  • index_or_name: This parameter can be:
  • An int representing the sheet’s position (1-based index). For example, 1 refers to the first sheet tab from the left.
  • A str representing the exact name of the sheet as it appears on its tab.

Unlike the VBA Item property, xlwings does not use a separate property call; the indexing is performed directly on the sheets collection.

Code Examples
Here are practical examples demonstrating how to use this functionality in xlwings:

  1. Accessing a sheet by its index:
import xlwings as xw
# Connect to an existing workbook (ensure Excel is open or use app.books.open)
app = xw.App(visible=False)
wb = app.books.open(r'C:\path\to\your\workbook.xlsx')
# Access the first worksheet in the workbook
first_sheet = wb.sheets[1]
# Read a value from cell A1 of the first sheet
value_a1 = first_sheet.range('A1').value
print(value_a1)
wb.close()
app.quit()
  1. Accessing a sheet by its name:
import xlwings as xw
# Start a new instance of Excel and create a new workbook
app = xw.App()
wb = app.books.add()
# Rename the first sheet for demonstration
wb.sheets[0].name = 'SalesData'
# Access the sheet by its exact name
sales_sheet = wb.sheets['SalesData']
# Write a value to cell B5
sales_sheet.range('B5').value = 'Quarterly Revenue'
# Save and close
wb.save('report.xlsx')
wb.close()
app.quit()
  1. Iterating through all sheets using the collection:
    While the Item concept is for single access, you can loop through the sheets collection, which is the parent of the Item.
import xlwings as xw
wb = xw.Book('data_workbook.xlsx')
# Print the name of every sheet in the workbook
for sheet in wb.sheets:
    print(sheet.name)
    # You could perform operations on each 'sheet' object here
wb.close()

August 18, 2026 (0)


Leave a Reply

Your email address will not be published. Required fields are marked *