auto_fit_table_columns
Adjusts table column widths in Word documents to fit content automatically. Specify the filename and table index to apply precise formatting.
Instructions
Set table columns to auto-fit based on content.
Input Schema
| Name | Required | Description | Default |
|---|---|---|---|
| filename | Yes | ||
| table_index | Yes |
Input Schema (JSON Schema)
{
"properties": {
"filename": {
"title": "Filename",
"type": "string"
},
"table_index": {
"title": "Table Index",
"type": "integer"
}
},
"required": [
"filename",
"table_index"
],
"type": "object"
}
Implementation Reference
- word_document_server/main.py:436-439 (registration)Registration of the MCP tool 'auto_fit_table_columns' using @mcp.tool() decorator. This is a thin wrapper that delegates to the implementation in format_tools.@mcp.tool() def auto_fit_table_columns(filename: str, table_index: int): """Set table columns to auto-fit based on content.""" return format_tools.auto_fit_table_columns(filename, table_index)
- Main handler function for auto_fit_table_columns tool. Performs input validation, loads the document, retrieves the specified table, calls the core auto_fit_table helper, saves the document, and returns success/error message.async def auto_fit_table_columns(filename: str, table_index: int) -> str: """Set table columns to auto-fit based on content. Args: filename: Path to the Word document table_index: Index of the table (0-based) """ filename = ensure_docx_extension(filename) # Ensure numeric parameters are the correct type try: table_index = int(table_index) except (ValueError, TypeError): return "Invalid parameter: table_index must be an integer" 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 auto-fit success = auto_fit_table(table) if success: doc.save(filename) return f"Table {table_index} set to auto-fit columns based on content." else: return f"Failed to set table auto-fit." except Exception as e: return f"Failed to set table auto-fit: {str(e)}"
- Core helper function that implements the auto-fit logic by manipulating the table's XML properties to set 'autofit' layout and auto widths for all columns.def auto_fit_table(table): """ Set table to auto-fit columns based on content. Args: table: The table to modify Returns: True if successful, False otherwise """ try: # Get table element and properties tbl = table._tbl # Get or create table properties tbl_pr = tbl.find(qn('w:tblPr')) if tbl_pr is None: tbl_pr = OxmlElement('w:tblPr') tbl.insert(0, tbl_pr) # Remove existing layout existing_layout = tbl_pr.find(qn('w:tblLayout')) if existing_layout is not None: tbl_pr.remove(existing_layout) # Create auto layout element layout_element = OxmlElement('w:tblLayout') layout_element.set(qn('w:type'), 'autofit') tbl_pr.append(layout_element) # Set all column widths to auto for col_index in range(len(table.columns)): set_column_width(table, col_index, 0, "auto") return True except Exception as e: print(f"Error setting auto-fit table: {e}") return False