set_table_column_width
Adjust table column width in Word documents to improve readability and formatting. Specify filename, table index, column index, and desired width for precise control.
Instructions
Set the width of a specific table column.
Input Schema
TableJSON Schema
| Name | Required | Description | Default |
|---|---|---|---|
| filename | Yes | ||
| table_index | Yes | ||
| col_index | Yes | ||
| width | Yes | ||
| width_type | No | points |
Implementation Reference
- word_document_server/main.py:418-422 (registration)MCP tool registration for set_table_column_width using @mcp.tool(). Defines input schema via type hints and docstring. Thin handler delegates to format_tools implementation.@mcp.tool() def set_table_column_width(filename: str, table_index: int, col_index: int, width: float, width_type: str = "points"): """Set the width of a specific table column.""" return format_tools.set_table_column_width(filename, table_index, col_index, width, width_type)
- Primary handler logic: validates inputs, handles document loading/saving, converts width units to Word XML format (dxa/pct), delegates low-level XML manipulation to core.tables.set_column_width_by_position.async def set_table_column_width(filename: str, table_index: int, col_index: int, width: float, width_type: str = "points") -> str: """Set the width of a specific table column. Args: filename: Path to the Word document table_index: Index of the table (0-based) col_index: Column index (0-based) width: Column width value width_type: Width type ("points", "inches", "cm", "percent", "auto") """ filename = ensure_docx_extension(filename) # Ensure numeric parameters are the correct type try: table_index = int(table_index) col_index = int(col_index) if width_type != "auto": width = float(width) except (ValueError, TypeError): return "Invalid parameter: table_index and col_index must be integers, width must be a number" # Validate width type valid_width_types = ["points", "inches", "cm", "percent", "auto"] if width_type.lower() not in valid_width_types: return f"Invalid width type. Valid options: {', '.join(valid_width_types)}" 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] # Validate column index if col_index < 0 or col_index >= len(table.columns): return f"Invalid column index. Table has {len(table.columns)} columns (0-{len(table.columns)-1})." # Convert width and type for Word format if width_type.lower() == "points": # Points to DXA (twentieths of a point) word_width = width word_type = "dxa" elif width_type.lower() == "inches": # Inches to points, then to DXA word_width = width * 72 # 72 points per inch word_type = "dxa" elif width_type.lower() == "cm": # CM to points, then to DXA word_width = width * 28.35 # ~28.35 points per cm word_type = "dxa" elif width_type.lower() == "percent": # Percentage (Word uses 50x the percentage value) word_width = width word_type = "pct" else: # auto word_width = 0 word_type = "auto" # Apply column width success = set_column_width_by_position(table, col_index, word_width, word_type) if success: doc.save(filename) return f"Column width set successfully for table {table_index}, column {col_index} to {width} {width_type}." else: return f"Failed to set column width. Check that indices are valid." except Exception as e: return f"Failed to set column width: {str(e)}"
- Low-level helper that directly modifies the Word document XML (w:tcW elements in tcPr for each cell in the column) to set the column width. Performs unit conversion to DXA/PCT and handles XML manipulation.def set_column_width(table, col_index, width, width_type="dxa"): """ Set the width of a specific column in a table. Args: table: The table to modify col_index: Column index (0-based) width: Column width value width_type: Width type ("dxa" for points*20, "pct" for percentage*50, "auto") Returns: True if successful, False otherwise """ try: # Validate column index if col_index < 0 or col_index >= len(table.columns): return False # Convert width based on type if width_type == "dxa": # DXA units (twentieths of a point) if isinstance(width, (int, float)): width_value = str(int(width * 20)) else: width_value = str(width) elif width_type == "pct": # Percentage (multiply by 50 for Word format) if isinstance(width, (int, float)): width_value = str(int(width * 50)) else: width_value = str(width) else: width_value = str(width) # Iterate through all rows and set width for cells in the specified column for row in table.rows: if col_index < len(row.cells): cell = row.cells[col_index] tc_pr = cell._tc.get_or_add_tcPr() # Remove existing width existing_width = tc_pr.find(qn('w:tcW')) if existing_width is not None: tc_pr.remove(existing_width) # Create new width element width_element = OxmlElement('w:tcW') width_element.set(qn('w:w'), width_value) width_element.set(qn('w:type'), width_type) tc_pr.append(width_element) return True except Exception as e: print(f"Error setting column width: {e}") return False