From 15fab96d4ae8b28054672f0fe55c2617d3717be7 Mon Sep 17 00:00:00 2001 From: Lieven De Foor Date: Tue, 16 Jun 2026 16:33:08 +0200 Subject: [PATCH] Fix column width distortion in AutoFit with active AutoFilter --- src/EPPlus/Core/AutofitHelper.cs | 2 +- src/EPPlusTest/WorkSheetTests.cs | 21 +++++++++++++++++++++ 2 files changed, 22 insertions(+), 1 deletion(-) diff --git a/src/EPPlus/Core/AutofitHelper.cs b/src/EPPlus/Core/AutofitHelper.cs index a121b3480b..e10eea5ab4 100644 --- a/src/EPPlus/Core/AutofitHelper.cs +++ b/src/EPPlus/Core/AutofitHelper.cs @@ -126,7 +126,7 @@ internal void AutofitColumn(double MinimumWidth, double MaximumWidth) { if (af.Collide(fromRow, col, toRow, col) != eAddressCollition.No) { - var cell = worksheet.Cells[af.Address]; + var cell = worksheet.Cells[af._fromRow, col]; var cellStyleId = styles.CellXfs[cell.StyleID]; currentMaxWidth = GetTextLength(cell, textLengthCache, styles, cellStyleId, normalSize, MaximumWidth, currentMaxWidth); } diff --git a/src/EPPlusTest/WorkSheetTests.cs b/src/EPPlusTest/WorkSheetTests.cs index ed53a0be5f..05db9a4ca7 100644 --- a/src/EPPlusTest/WorkSheetTests.cs +++ b/src/EPPlusTest/WorkSheetTests.cs @@ -2181,6 +2181,27 @@ public void AutoFitColumnTest() SaveAndCleanup(p); } [TestMethod] + public void AutoFitColumnsWithAutoFilter() + { + var ws = _pck.Workbook.Worksheets.Add("AutofitAutoFilter"); + ws.Cells["A1"].Value = "hour"; + ws.Cells["B1"].Value = "minute"; + ws.Cells["A2"].Value = 12; + ws.Cells["B2"].Value = 30; + + ws.Cells["A1:B2"].AutoFilter = true; + + ws.Cells["A1:B2"].AutoFitColumns(); + + // Without the fix, the AutoFilter header row range (A1:B1) is measured as a whole. + // Under the hood, worksheet.Cells["A1:B1"].TextForWidth evaluated to "System.Object[,]" (16 chars), + // which forced a minimum width of ~16.07 points. + // With the fix, the specific cell for each column in the AutoFilter is measured, + // resulting in a narrow width matching "hour" / "minute". + Assert.IsTrue(ws.Column(1).Width < 12d, $"Column 1 width should be small but was {ws.Column(1).Width}"); + Assert.IsTrue(ws.Column(2).Width < 12d, $"Column 2 width should be small but was {ws.Column(2).Width}"); + } + [TestMethod] public void CopyOverwrite() { var ws = _pck.Workbook.Worksheets.Add("CopyOverwrite");