Skip to content

feat(core): Add AWT-based font measurement for accurate autofit #156

@arcaputo3

Description

@arcaputo3

Summary

Add pixel-accurate column width calculation using Java AWT font metrics, similar to Apache POI's autoSizeColumn implementation.

Background

PR #155 added basic autofit using charCount * 0.85 + 1.5 heuristic. This works but produces widths ~5-10% wider than Excel's actual autofit.

Proposed Solution

  • Create FontMetrics utility using AWT TextLayout + FontRenderContext
  • Graceful fallback to heuristic in headless environments
  • Style-aware: respects font family, size, bold/italic from cell styles

Technical Approach (POI-style)

  • Excel uses "character units" based on max digit width of default font
  • Calibri 11pt at 96 DPI: max digit width ≈ 7 pixels
  • Formula: width = (pixels + 5) / maxDigitWidth
  • +5 padding: 2px left margin + 2px right margin + 1px gridline

Implementation

  1. New file: xl-core/src/com/tjclp/xl/util/FontMetrics.scala
  2. Integrate into WriteCommands.calculateAutoFitWidth()
  3. Add tests for AWT and fallback modes

Acceptance Criteria

  • AWT measurement within 5% of Excel's autofit
  • Fallback works in headless/CI environments
  • All existing autofit tests pass
  • Performance: <100ms for 1000 cells

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or request

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions