How to use Worksheet.Name in the xlwings API way

The Name property of a Worksheet object in the Excel object model is a fundamental attribute used to get or set the name of a worksheet. In xlwings, this property is accessed directly through the Worksheet object, allowing for straightforward retrieval and modification of sheet names within a workbook. This capability is essential for tasks such as dynamically referencing sheets, organizing data across multiple sheets, or automating sheet management processes.

Functionality:
The primary function is to read or change the name of a worksheet. This is useful in scenarios where sheet names need to be updated based on data content, user input, or automated workflows. For example, you might rename sheets after importing data to reflect the dataset’s source or date.

Syntax in xlwings:
In xlwings, the Name property is accessed as an attribute of a Worksheet object. The syntax is simple:

  • To get the current name: sheet_name = ws.name
  • To set a new name: ws.name = "NewSheetName"
    Here, ws represents a Worksheet object obtained via wb.sheets['Sheet1'] or similar. The name must be a string and adhere to Excel’s naming conventions (e.g., no more than 31 characters, and characters like :, \, /, ?, *, [, ] are not allowed). If an invalid name is provided, xlwings will raise an error.

Code Examples:
Below are practical examples demonstrating the use of the Name property with xlwings.

  1. Retrieving a Worksheet Name:
    This example opens an existing workbook and prints the name of the first worksheet.
import xlwings as xw
# Open an existing workbook
wb = xw.Book('example.xlsx')
# Access the first worksheet
ws = wb.sheets[0]
# Get and print the worksheet name
current_name = ws.name
print(f"The worksheet name is: {current_name}")
  1. Renaming a Worksheet:
    This example renames a specific worksheet to “DataSummary”.
import xlwings as xw
# Open an existing workbook
wb = xw.Book('example.xlsx')
# Access a worksheet by its current name
ws = wb.sheets['Sheet1']
# Change the worksheet name
ws.name = "DataSummary"
# Save the workbook to persist changes
wb.save()
  1. Dynamic Renaming Based on Content:
    This example renames all worksheets in a workbook based on a list of new names, demonstrating batch processing.
import xlwings as xw
# Open an existing workbook
wb = xw.Book('data.xlsx')
# Define new names for each worksheet
new_names = ["January", "February", "March"]
# Iterate through worksheets and rename them
for i, ws in enumerate(wb.sheets):
    if i < len(new_names):
        ws.name = new_names[i]
# Save the workbook
wb.save()

September 25, 2026 (0)


Leave a Reply

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