A Python module for creating Excel XLSX files.
Core workbook functionality for creating, configuring, and managing Excel files. The Workbook class is the main entry point for XlsxWriter and provides methods for creating worksheets, formats, charts, and managing global workbook settings.
Create and finalize Excel workbooks with optional configuration settings.
class Workbook:
def __init__(self, filename, options=None):
"""
Create a new Excel workbook.
Args:
filename (str): The name of the new Excel file to create
options (dict, optional): Workbook options including:
- constant_memory: Enable memory optimization mode
- tmpdir: Directory for temporary files
- date_1904: Use 1904 date system
- default_date_format: Default date format string
- remove_timezone: Remove timezone from datetime objects
- nan_inf_to_errors: Convert NaN/Inf to Excel errors
- strings_to_numbers: Convert number strings to numbers
- strings_to_formulas: Convert formula strings to formulas
- strings_to_urls: Convert URL strings to hyperlinks
- use_future_functions: Enable future Excel functions
- max_url_length: Maximum URL length
- nan_inf_to_errors: Handle NaN/Inf values
"""
def close(self):
"""
Close the workbook and write the Excel file.
This method writes all worksheets and metadata to the Excel file
and must be called to save the workbook properly.
"""Create and manage worksheets within the workbook.
def add_worksheet(self, name=None, worksheet_class=None):
"""
Add a new worksheet to the workbook.
Args:
name (str, optional): Name for the worksheet. Auto-generated if None
worksheet_class (class, optional): Custom worksheet class to use
Returns:
Worksheet: The created worksheet object
"""
def add_chartsheet(self, name=None, chartsheet_class=None):
"""
Add a new chartsheet to the workbook.
Args:
name (str, optional): Name for the chartsheet. Auto-generated if None
chartsheet_class (class, optional): Custom chartsheet class to use
Returns:
Chartsheet: The created chartsheet object
"""
def worksheets(self):
"""
Get a list of all worksheets in the workbook.
Returns:
list: List of worksheet objects
"""
def get_worksheet_by_name(self, name):
"""
Get a worksheet by its name.
Args:
name (str): Name of the worksheet to retrieve
Returns:
Worksheet: The worksheet object or None if not found
"""Create formatting and chart objects for use throughout the workbook.
def add_format(self, properties=None):
"""
Create a new Format object for cell formatting.
Args:
properties (dict, optional): Dictionary of format properties
Returns:
Format: A new format object that can be applied to cells
"""
def add_chart(self, options):
"""
Create a new Chart object.
Args:
options (dict): Chart options including:
- type: Chart type ('column', 'line', 'pie', 'scatter', etc.)
- subtype: Chart subtype for specific variations
Returns:
Chart: A chart object of the specified type
"""
def get_default_url_format(self):
"""
Get the default hyperlink format.
Returns:
Format: The default blue, underlined hyperlink format
"""Configure workbook-level properties and settings.
def set_properties(self, properties):
"""
Set document properties for the workbook.
Args:
properties (dict): Document properties including:
- title: Document title
- subject: Document subject
- author: Document author
- manager: Document manager
- company: Company name
- category: Document category
- keywords: Document keywords
- comments: Document comments
- status: Document status
- hyperlink_base: Base URL for relative hyperlinks
- created: Creation date (datetime object)
"""
def set_custom_property(self, name, value, property_type=None):
"""
Set a custom document property.
Args:
name (str): Property name
value: Property value (str, int, float, bool, or datetime)
property_type (str, optional): Force property type
"""
def set_calc_mode(self, mode, calc_id=None):
"""
Set the calculation mode for the workbook.
Args:
mode (str): Calculation mode ('automatic', 'manual', 'automatic_except_tables')
calc_id (int, optional): Calculation chain ID
"""
def define_name(self, name, formula):
"""
Create a defined name in the workbook.
Args:
name (str): The defined name
formula (str): The formula or range the name refers to
"""Control workbook window appearance and behavior.
def set_size(self, width, height):
"""
Set the size of the workbook window in pixels.
Args:
width (int): Window width in pixels
height (int): Window height in pixels
"""
def set_tab_ratio(self, tab_ratio=None):
"""
Set the ratio between worksheet tabs and horizontal scrollbar.
Args:
tab_ratio (float): Ratio from 0.0 to 1.0 (default 0.6)
"""
def read_only_recommended(self):
"""
Set the workbook to open with a read-only recommendation dialog.
"""Add VBA projects and macros to the workbook.
def add_vba_project(self, vba_project, is_stream=False):
"""
Add a VBA project to the workbook.
Args:
vba_project (str or bytes): Path to VBA file or VBA binary data
is_stream (bool): True if vba_project is binary data
"""
def add_signed_vba_project(self, vba_project, signature, project_is_stream=False, signature_is_stream=False):
"""
Add a signed VBA project to the workbook.
Args:
vba_project (str or bytes): Path to VBA file or VBA binary data
signature (str or bytes): Path to signature file or signature data
project_is_stream (bool): True if vba_project is binary data
signature_is_stream (bool): True if signature is binary data
"""
def set_vba_name(self, name=None):
"""
Set the VBA code name for the workbook.
Args:
name (str, optional): VBA code name for the workbook
"""Configure file-level options and optimizations.
def use_zip64(self):
"""
Enable ZIP64 extensions for large files (>4GB).
This allows creation of Excel files larger than the 4GB ZIP file limit
but requires Excel 2010 or later to read the files.
"""
def get_image_index(self, image):
"""
Get the index of an embedded image.
Args:
image (Image): The image object to lookup
Returns:
int: The image index for internal reference
Note: This is an internal method used by the embed_image functionality.
"""
def has_images(self):
"""
Check if the workbook has embedded images.
Returns:
bool: True if workbook contains embedded images, False otherwise
Note: This is an internal method used to optimize file creation.
"""import xlsxwriter
# Create workbook with options
workbook = xlsxwriter.Workbook('example.xlsx', {
'constant_memory': True, # Memory optimization
'default_date_format': 'dd/mm/yy'
})
# Add worksheets
sheet1 = workbook.add_worksheet('Data')
sheet2 = workbook.add_worksheet('Analysis')
# Create formats
bold = workbook.add_format({'bold': True})
currency = workbook.add_format({'num_format': '$#,##0.00'})
# Set properties
workbook.set_properties({
'title': 'Sales Report',
'author': 'John Doe',
'company': 'Example Corp'
})
# Close and save
workbook.close()# Create different chart types
chart1 = workbook.add_chart({'type': 'column'})
chart2 = workbook.add_chart({'type': 'line'})
chart3 = workbook.add_chart({'type': 'pie'})
# Configure and insert charts
chart1.add_series({'values': '=Sheet1!B2:B5'})
worksheet.insert_chart('D2', chart1)# Add VBA project from file
workbook.add_vba_project('macros.bin')
# Set VBA code name
workbook.set_vba_name('ThisWorkbook')Install with Tessl CLI
npx tessl i tessl/pypi-xlsxwriter