How to use Workbooks.Add in the xlwings API way
The Add member of the Workbooks object in the Excel object model is a method used to create a new, empty workbook. In xlwings, this functionality is accessed through the xlwings.Book() constructor, which internally leverages the Add method when creating a new workbook without opening an existing file. This is a fundamental operation for automating report generation, data processing workflows, or any task that requires starting with a fresh Excel file programmatically.
Functionality
The primary purpose is to instantiate a new Excel workbook. This new workbook becomes the active workbook in the Excel application and contains a default number of worksheets (typically one, depending on Excel’s default settings). It provides a clean slate for subsequent operations like data entry, formatting, or chart creation.
Syntax and Parameters
In xlwings, you do not call Add directly on a Workbooks collection. Instead, you create a new Book object. The equivalent action is performed with the following syntax:
import xlwings as xw
new_workbook = xw.Book()
This constructor corresponds to the VBA Workbooks.Add() method. The xlwings Book() constructor can also accept a template argument to create a workbook based on an existing template file.
template(optional, string): The full path to an Excel template file (.xltx,.xltm). If provided, the new workbook is created as a copy of this template. If omitted, a new blank workbook is created based on the default workbook template.
Code Examples
- Creating a Blank Workbook:
This is the most straightforward use case. The code below starts Excel (if not already running), creates a new workbook, and returns aBookobject linked to it.
import xlwings as xw
# Create a new blank workbook
wb = xw.Book()
print(f"New workbook created: {wb.name}")
# Add data to the first worksheet
wb.sheets[0].range('A1').value = "Sample Data"
wb.sheets[0].range('A2').value = 100
# Save the workbook
wb.save(r'C:\path\to\NewReport.xlsx')
wb.close()
- Creating a Workbook from a Template:
This is useful for standardized reports where formatting, headers, or specific sheet structures are pre-defined in a template file.
import xlwings as xw
# Path to your template file
template_path = r'C:\templates\Monthly_Report_Template.xltx'
# Create a new workbook based on the template
wb = xw.Book(template_path)
print(f"Workbook created from template: {wb.name}")
# The new workbook inherits all sheets and formatting from the template.
# You can now populate it with data.
wb.sheets['Data'].range('B5').value = "Q4 Results"
# ... additional data processing ...
# Save it as a regular workbook
wb.save(r'C:\reports\Monthly_Report_November.xlsx')