### Install xltpl Source: https://github.com/zhangyu836/xltpl/blob/master/README.md Use pip to install the xltpl package. ```shell pip install xltpl ``` -------------------------------- ### Render Excel Template Source: https://github.com/zhangyu836/xltpl/blob/master/README.md Initialize a BookWriter, provide data, and save the rendered output to a new file. ```python from xltpl.writerx import BookWriter writer = BookWriter('tpl.xlsx') person_info = {'name': u'Hello Wizard'} items = ['1', '1', '1', '1', '1', '1', '1', '1', ] person_info['items'] = items payloads = [person_info] writer.render_book(payloads) writer.save('result.xlsx') ``` -------------------------------- ### Enable Debug Mode Source: https://context7.com/zhangyu836/xltpl/llms.txt Initialize BookWriter with debug=True to receive detailed error information, including cell locations, for template syntax errors. ```python from xltpl.writerx import BookWriter # Enable debug mode during initialization writer = BookWriter('template.xlsx', debug=True) # When a Jinja2 syntax error occurs, debug output shows: # - The line number in the generated template # - The cell address (e.g., "B5") where the error occurred # - The cell content that caused the error # - Surrounding context for easier debugging data = { 'items': [1, 2, 3], 'sheet_name': 'Debug Test' } try: writer.render_sheet(data) writer.save('output.xlsx') except Exception as e: print(f"Template error: {e}") ``` -------------------------------- ### Implement Nested Loops Source: https://context7.com/zhangyu836/xltpl/llms.txt Use nested loops for matrix-style output. Preserve outer loop context using the set tag. ```python from xltpl.writerx import BookWriter writer = BookWriter('matrix_template.xlsx') data = { 'rows': ['A', 'B', 'C'], 'cols': [1, 2, 3, 4], 'sheet_name': 'Matrix' } writer.render_sheet(data) writer.save('matrix_output.xlsx') ``` -------------------------------- ### Position Layouts with Box Objects Source: https://context7.com/zhangyu836/xltpl/llms.txt Use the Box object returned by render_sheet to calculate coordinates for precise section placement. ```python from xltpl.writerx import BookWriter writer = BookWriter('layout_template.xlsx') data = { 'items': [ {'name': 'Item 1', 'value': 100}, {'name': 'Item 2', 'value': 200}, ], 'sheet_name': 'Dashboard' } # Render header section at default position (top-left) data['tpl_name'] = 'header' header_box = writer.render_sheet(data, None) # Render left sidebar below header data['tpl_name'] = 'sidebar' left_box = writer.render_sheet(data, (header_box.bottom, header_box.left)) # Render main content to the right of sidebar data['tpl_name'] = 'content' content_box = writer.render_sheet(data, (left_box.top, left_box.right)) # Render footer below all sections data['tpl_name'] = 'footer' footer_top = max(left_box.bottom, content_box.bottom) writer.render_sheet(data, (footer_top, header_box.left)) writer.save('dashboard_output.xlsx') ``` -------------------------------- ### Render Excel Sheet with Data Source: https://context7.com/zhangyu836/xltpl/llms.txt Basic usage of BookWriter to render a list of objects into an Excel template. ```python from xltpl.writerx import BookWriter from datetime import datetime class Item: def __init__(self, name, category, price, count): self.name = name self.category = category self.price = price self.count = count writer = BookWriter('product_list_template.xlsx') items = [ Item("Apple", "Fruit", 1.50, 100), Item("Carrot", "Vegetable", 0.80, 200), Item("Banana", "Fruit", 0.60, 150), Item("Potato", "Vegetable", 0.40, 300), ] data = { 'items': items, 'sheet_name': 'Products' } writer.render_sheet(data) writer.save('product_list_output.xlsx') ``` -------------------------------- ### Generate xlsx Files with BookWriter Source: https://context7.com/zhangyu836/xltpl/llms.txt Use BookWriter from xltpl.writerx to load an xlsx template, render data into it using Jinja2 syntax, and save the result. This is the primary class for modern Excel file generation. ```python from xltpl.writerx import BookWriter from datetime import datetime # Load the xlsx template writer = BookWriter('template.xlsx') # Prepare data payload with template variables data = { 'name': 'John Doe', 'address': '123 Main Street', 'date': datetime.now(), 'items': [ {'product': 'Widget A', 'price': 10.99, 'quantity': 5}, {'product': 'Widget B', 'price': 24.50, 'quantity': 2}, {'product': 'Gadget C', 'price': 15.00, 'quantity': 10}, ], 'sheet_name': 'Invoice' # Output sheet name } # Render the template with data writer.render_sheet(data) # Save the output file writer.save('output.xlsx') ``` -------------------------------- ### Loops and Control Statements in Templates Source: https://context7.com/zhangyu836/xltpl/llms.txt Use Jinja2 control statements like `{%- for %}` directly in Excel cells to create dynamic rows by iterating over collections. This is useful for generating tables with variable numbers of rows. ```python # Template cell contents for a table with dynamic rows: # Row 1: Headers (Name, Category, Price, Quantity) # Row 2, Cell A2: "{%- for item in items %}{{item.name}}" ``` -------------------------------- ### Register Global Functions Source: https://context7.com/zhangyu836/xltpl/llms.txt Make Python functions available within template cells using add_global or set_jinja_globals. ```python from xltpl.writerx import BookWriter writer = BookWriter('template.xlsx') # Add built-in functions as globals writer.set_jinja_globals( dir=dir, getattr=getattr, len=len, sum=sum ) # Add custom function def calculate_tax(amount, rate=0.1): return amount * rate writer.add_global('tax', calculate_tax) # Template cell: "{% xv tax(subtotal, 0.08) %}" data = { 'subtotal': 100.00, 'items': [10, 20, 30], 'sheet_name': 'Calculations' } writer.render_sheet(data) writer.save('output.xlsx') ``` -------------------------------- ### Render Multiple Data Sets to One Sheet Source: https://context7.com/zhangyu836/xltpl/llms.txt Append multiple sections to a single sheet by tracking the box coordinates returned by render_sheet. ```python from xltpl.writerx import BookWriter writer = BookWriter('report_template.xlsx') # Multiple report sections on one sheet sections = [ {'title': 'Q1 Report', 'revenue': 50000, 'tpl_name': 'quarter'}, {'title': 'Q2 Report', 'revenue': 62000, 'tpl_name': 'quarter'}, {'title': 'Q3 Report', 'revenue': 71000, 'tpl_name': 'quarter'}, ] top_left = None for section in sections: section['sheet_name'] = 'Annual Summary' box = writer.render_sheet(section, top_left) # Position next section below the previous one top_left = (box.bottom, box.left) writer.save('annual_report.xlsx') ``` -------------------------------- ### Insert Control Statements via Comments Source: https://github.com/zhangyu836/xltpl/blob/master/README.md Use beforerow tags within cell comments to control loop execution. ```jinja2 beforerow{% for item in items %} ``` ```jinja2 beforerow{% endfor %} ``` -------------------------------- ### Template Syntax for Variables and Types Source: https://context7.com/zhangyu836/xltpl/llms.txt Insert variables into Excel cells using Jinja2 syntax. Use {{variable}} for string values and {% xv variable %} for non-string values like numbers and dates to preserve their type. ```python # Template cell contents (in the xlsx/xls file): # Cell A1: "Name: {{name}}" # Cell B1: "Total: {% xv total %}" (preserves numeric type) # Cell C1: "Date: {{date}}" from xltpl.writerx import BookWriter from datetime import datetime writer = BookWriter('invoice_template.xlsx') data = { 'name': 'Acme Corp', 'total': 15750.50, # Will be written as number, not string 'date': datetime(2024, 1, 15), 'sheet_name': 'Invoice' } writer.render_sheet(data) writer.save('invoice_output.xlsx') ``` -------------------------------- ### Generate xls Files with BookWriter Source: https://context7.com/zhangyu836/xltpl/llms.txt Use BookWriter from xltpl.writer to handle legacy xls file generation. It uses xlrd for reading and xlwt for writing, providing a consistent API with the xlsx version. ```python from xltpl.writer import BookWriter from datetime import datetime # Load the xls template writer = BookWriter('template.xls') # Prepare data payload data = { 'name': 'Jane Smith', 'address': '456 Oak Avenue', 'date': datetime.now(), 'total': 1250.00, 'sheet_name': 'Report' } # Render and save writer.render_sheet(data) writer.save('output.xls') ``` -------------------------------- ### Render Multiple Sheets in a Workbook Source: https://context7.com/zhangyu836/xltpl/llms.txt Utilize render_sheets or render_book methods to generate multiple sheets within a single workbook. Each payload can specify a different template and output sheet name. ```python from xltpl.writerx import BookWriter from datetime import datetime writer = BookWriter('multi_template.xlsx') # First sheet using template index 0 sheet1_data = { 'name': 'Customer A', 'items': [{'item': 'Product 1', 'qty': 10}], 'sheet_name': 'CustomerA', 'tpl_index': 0 # Use first template sheet } # Second sheet using template index 1 sheet2_data = { 'name': 'Customer B', 'items': [{'item': 'Product 2', 'qty': 5}], 'sheet_name': 'CustomerB', 'tpl_index': 1 # Use second template sheet } # Third sheet referencing template by name sheet3_data = { 'name': 'Summary', 'total_customers': 2, 'sheet_name': 'Summary', 'tpl_name': 'summary_template' # Use template by name } # Render all sheets at once payloads = [sheet1_data, sheet2_data, sheet3_data] writer.render_sheets(payloads) # Or use render_book (equivalent) # writer.render_book(payloads) writer.save('multi_sheet_output.xlsx') ``` -------------------------------- ### Embed Images in XLSX Source: https://context7.com/zhangyu836/xltpl/llms.txt Insert images into Excel files using the {% img %} tag with file paths or PIL objects. ```python from xltpl.writerx import BookWriter from PIL import Image as PILImage writer = BookWriter('template_with_images.xlsx') # Load image from file or as PIL object logo_path = 'images/company_logo.jpg' product_image = PILImage.open('images/product.jpg') # Template cell: "{% img logo %}" or "{% img product_img %}" data = { 'company_name': 'Acme Corp', 'logo': logo_path, # File path 'product_img': product_image, # PIL Image object 'sheet_name': 'Catalog' } writer.render_sheet(data) writer.save('catalog_output.xlsx') ``` -------------------------------- ### Add Custom Jinja2 Filters Source: https://context7.com/zhangyu836/xltpl/llms.txt Register custom Python functions as Jinja2 filters to transform cell data during rendering. ```python from xltpl.writerx import BookWriter writer = BookWriter('template.xlsx') # Add custom filter for currency formatting def currency(value): return f"${value:,.2f}" # Add custom filter for uppercase def shout(value): return str(value).upper() writer.add_filter('currency', currency) writer.add_filter('shout', shout) # Template cell: "{{total|currency}}" -> "$1,234.56" # Template cell: "{{name|shout}}" -> "JOHN DOE" data = { 'name': 'John Doe', 'total': 1234.56, 'sheet_name': 'Report' } writer.render_sheet(data) writer.save('output.xlsx') ``` -------------------------------- ### Insert Jinja2 Variables Source: https://github.com/zhangyu836/xltpl/blob/master/README.md Insert variables directly into Excel cells using standard Jinja2 syntax. ```jinja2 {{name}} ``` -------------------------------- ### Insert Control Statements in Cells Source: https://github.com/zhangyu836/xltpl/blob/master/README.md Use Jinja2 control structures directly within cells for complex data rendering. ```jinja2 {%- for row in rows %} {% set outer_loop = loop %}{% for row in rows %} Cell {{outer_loop.index}}{{loop.index}} {%+ endfor%}{%+ endfor%} ``` -------------------------------- ### Apply Cell Style Filters for XLS Source: https://context7.com/zhangyu836/xltpl/llms.txt Use the @add_filter decorator to define custom functions that modify cell styles during rendering for xls files. ```python import copy import xlwt from jinja2 import pass_environment from xltpl.filters import add_filter from xltpl.writer import BookWriter @pass_environment @add_filter def highlight(cell_context, condition=None): """Highlight cell with yellow background if condition is true""" if condition: style = cell_context.get_style() pattern = copy.copy(style.pattern) pattern.pattern = xlwt.Pattern.SOLID_PATTERN pattern.pattern_fore_colour = xlwt.Style.colour_map['yellow'] style.pattern = pattern @pass_environment @add_filter def bold_text(cell_context, make_bold=True): """Make cell text bold""" if make_bold: style = cell_context.get_style() font = copy.copy(style.font) font.bold = True style.font = font writer = BookWriter('template.xls') writer.add_filter('highlight', highlight) writer.add_filter('bold_text', bold_text) writer.add_global('highlight', highlight) writer.add_global('bold_text', bold_text) # Template cell: "{{value|highlight(value > 100)}}" # Template cell: "{{name|bold_text(is_important)}}" data = { 'value': 150, 'name': 'Critical Item', 'is_important': True, 'sheet_name': 'Styled Report' } writer.render_sheet(data) writer.save('styled_output.xls') ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.