Skip to main content
Glama

format_table

Apply custom borders, shading, and structured formatting to tables in Word documents. Specify table index, header row, and design preferences to enhance document clarity and presentation.

Instructions

Format a table with borders, shading, and structure.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
border_styleNo
filenameYes
has_header_rowNo
shadingNo
table_indexYes

Implementation Reference

  • Main handler function that loads the document, validates the table index, applies table styling using the helper function, saves the document, and returns a status message.
    async def format_table(filename: str, table_index: int, has_header_row: Optional[bool] = None, border_style: Optional[str] = None, shading: Optional[List[List[str]]] = None) -> str: """Format a table with borders, shading, and structure. Args: filename: Path to the Word document table_index: Index of the table (0-based) has_header_row: If True, formats the first row as a header border_style: Style for borders ('none', 'single', 'double', 'thick') shading: 2D list of cell background colors (by row and column) """ filename = ensure_docx_extension(filename) if not os.path.exists(filename): return f"Document {filename} does not exist" # Check if file is writeable is_writeable, error_message = check_file_writeable(filename) if not is_writeable: return f"Cannot modify document: {error_message}. Consider creating a copy first." try: doc = Document(filename) # Validate table index if table_index < 0 or table_index >= len(doc.tables): return f"Invalid table index. Document has {len(doc.tables)} tables (0-{len(doc.tables)-1})." table = doc.tables[table_index] # Apply formatting success = apply_table_style(table, has_header_row, border_style, shading) if success: doc.save(filename) return f"Table at index {table_index} formatted successfully." else: return f"Failed to format table at index {table_index}." except Exception as e: return f"Failed to format table: {str(e)}"
  • MCP tool registration using @mcp.tool() decorator. Defines the tool schema via parameters and docstring, and delegates execution to the implementation in format_tools.py.
    @mcp.tool() async def format_table(filename: str, table_index: int, has_header_row: Optional[bool] = None, border_style: Optional[str] = None, shading: Optional[List[str]] = None): """Format a table with borders, shading, and structure.""" return await format_tools.format_table(filename, table_index, has_header_row, border_style, shading)
  • Core helper function that performs the actual table formatting: makes header bold, applies borders to cells, and sets cell shading using low-level docx XML manipulation.
    def apply_table_style(table, has_header_row=False, border_style=None, shading=None): """ Apply formatting to a table. Args: table: The table to format has_header_row: If True, formats the first row as a header border_style: Style for borders ('none', 'single', 'double', 'thick') shading: 2D list of cell background colors (by row and column) Returns: True if successful, False otherwise """ try: # Format header row if requested if has_header_row and table.rows: header_row = table.rows[0] for cell in header_row.cells: for paragraph in cell.paragraphs: if paragraph.runs: for run in paragraph.runs: run.bold = True # Apply border style if specified if border_style: val_map = { 'none': 'nil', 'single': 'single', 'double': 'double', 'thick': 'thick' } val = val_map.get(border_style.lower(), 'single') # Apply to all cells for row in table.rows: for cell in row.cells: set_cell_border( cell, top=True, bottom=True, left=True, right=True, val=val, color="000000" ) # Apply cell shading if specified if shading: for i, row_colors in enumerate(shading): if i >= len(table.rows): break for j, color in enumerate(row_colors): if j >= len(table.rows[i].cells): break try: # Apply shading to cell cell = table.rows[i].cells[j] shading_elm = parse_xml(f'<w:shd {nsdecls("w")} w:fill="{color}"/>') cell._tc.get_or_add_tcPr().append(shading_elm) except: # Skip if color format is invalid pass return True except Exception: return False
  • Exposes the format_table function from format_tools.py for import in the main server file.
    from word_document_server.tools.format_tools import ( format_text, create_custom_style, format_table )

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/franlealp1/mcp-word'

If you have feedback or need assistance with the MCP directory API, please join our Discord server