format_cells
Apply formatting to Excel cells including fonts, colors, borders, alignment, and number formats to improve data presentation and readability.
Instructions
Apply formatting to Excel cells (fonts, colors, borders, alignment)
Input Schema
TableJSON Schema
| Name | Required | Description | Default |
|---|---|---|---|
| filePath | Yes | Path to the Excel file (.xlsx or .xls) | |
| range | Yes | Cell range in A1 notation (e.g., "A1", "A1:C5", "B2:D10") | |
| styling | Yes | Formatting options to apply | |
| sheet | No | Sheet name (optional, defaults to first sheet) |
Implementation Reference
- src/handlers/file-operations.ts:292-419 (handler)The primary handler function for the format_cells tool. It loads an Excel workbook, parses the specified range using A1 notation, applies comprehensive cell styling including font properties, fill, borders, alignment, and number formatting to each cell in the range, then saves the modified workbook and returns a success response with details.async formatCells(args: ToolArgs): Promise<ToolResponse> { const { filePath, range, styling, sheet } = args; const ext = path.extname(filePath).toLowerCase(); const absolutePath = path.resolve(filePath); if (ext !== '.xlsx' && ext !== '.xls') { throw new Error('Cell formatting only works with Excel files (.xlsx or .xls)'); } try { await fs.access(absolutePath); } catch { throw new Error(`File not found: ${filePath}`); } // Read existing workbook const workbook = new ExcelJS.Workbook(); await workbook.xlsx.readFile(absolutePath); // Get the worksheet const worksheet = sheet ? workbook.getWorksheet(sheet) : workbook.getWorksheet(1); if (!worksheet) { throw new Error(`Sheet "${sheet || 'first sheet'}" not found`); } // Parse range (e.g., "A1:C5" or "B2") let startCell: { row: number; col: number }; let endCell: { row: number; col: number }; if (range.includes(':')) { const [start, end] = range.split(':'); const startParsed = parseA1Notation(start); const endParsed = parseA1Notation(end); // Convert to 1-based indexing for ExcelJS startCell = { row: startParsed.row + 1, col: startParsed.col + 1 }; endCell = { row: endParsed.row + 1, col: endParsed.col + 1 }; } else { const parsed = parseA1Notation(range); // Convert to 1-based indexing for ExcelJS startCell = endCell = { row: parsed.row + 1, col: parsed.col + 1 }; } let formattedCells = 0; // Apply formatting to the range for (let row = startCell.row; row <= endCell.row; row++) { for (let col = startCell.col; col <= endCell.col; col++) { const cell = worksheet.getCell(row, col); // Apply font styling if (styling.font) { const fontStyle: any = {}; if (styling.font.bold !== undefined) fontStyle.bold = styling.font.bold; if (styling.font.italic !== undefined) fontStyle.italic = styling.font.italic; if (styling.font.underline !== undefined) fontStyle.underline = styling.font.underline; if (styling.font.size !== undefined) fontStyle.size = styling.font.size; if (styling.font.color !== undefined) fontStyle.color = { argb: styling.font.color }; if (styling.font.name !== undefined) fontStyle.name = styling.font.name; cell.font = { ...cell.font, ...fontStyle }; } // Apply fill (background color) if (styling.fill) { if (styling.fill.color) { cell.fill = { type: 'pattern', pattern: styling.fill.pattern || 'solid', fgColor: { argb: styling.fill.color } }; } } // Apply borders if (styling.border) { const borderStyle: any = {}; const borderConfig = { style: styling.border.style || 'thin', color: { argb: styling.border.color || 'FF000000' } }; if (styling.border.top !== false) borderStyle.top = borderConfig; if (styling.border.bottom !== false) borderStyle.bottom = borderConfig; if (styling.border.left !== false) borderStyle.left = borderConfig; if (styling.border.right !== false) borderStyle.right = borderConfig; cell.border = { ...cell.border, ...borderStyle }; } // Apply alignment if (styling.alignment) { const alignmentStyle: any = {}; if (styling.alignment.horizontal) alignmentStyle.horizontal = styling.alignment.horizontal; if (styling.alignment.vertical) alignmentStyle.vertical = styling.alignment.vertical; if (styling.alignment.wrapText !== undefined) alignmentStyle.wrapText = styling.alignment.wrapText; if (styling.alignment.textRotation !== undefined) alignmentStyle.textRotation = styling.alignment.textRotation; cell.alignment = { ...cell.alignment, ...alignmentStyle }; } // Apply number format if (styling.numberFormat) { cell.numFmt = styling.numberFormat; } formattedCells++; } } // Save the workbook await workbook.xlsx.writeFile(absolutePath); return { content: [ { type: 'text', text: JSON.stringify({ success: true, filePath: absolutePath, sheetName: worksheet.name, range, cellsFormatted: formattedCells, stylingApplied: Object.keys(styling), }, null, 2), }, ], }; }
- src/utils/file-utils.ts:7-20 (helper)Utility function parseA1Notation converts A1 cell notation (e.g., 'A1', 'C5') to zero-based {row, col} coordinates. Critically used in formatCells to parse start/end ranges for applying formatting.export function parseA1Notation(a1: string): CellAddress { const match = a1.match(/^([A-Z]+)(\d+)$/); if (!match) { throw new Error(`Invalid A1 notation: ${a1}`); } const col = match[1].split('').reduce((acc, char) => { return acc * 26 + char.charCodeAt(0) - 'A'.charCodeAt(0) + 1; }, 0) - 1; const row = parseInt(match[2]) - 1; return { row, col }; }