隐藏 EPPlus 中的列不起作用

Hide column in EPPlus not working

我想使用 EPPlus nuget 包隐藏 excel 中的一列,但它不起作用(它没有隐藏该列)

这就是我发现的可以解决问题的方法。也许有错误?

worksheet.Column(1).Hidden = true;

我使用的是 4.5.2.1 版本

项目URLhttps://github.com/JanKallman/EPPlus

我在打电话

worksheet.Cells.AutoFitColumns();

之后
worksheet.Column(1).Hidden = true;

AutoFitColumns 正在移除隐藏效果。

显然根据文档,您可以使用 AutoFitColumns(Double MinimumWidth, Double MaximumWidth):

Set the column width from the content of the range. Note: Cells containing formulas are ignored if no calculation is made. Wrapped and merged cells are also ignored. Hidden columns are left hidden.

    worksheet.Column(1).Hidden = true;
    worksheet.Cells.AutoFitColumns(8.43,100); // 8.43 = default width of cells

I'm pretty sure it's a bug.

截至撰写本文时 (2019-10-24),AutoFitColumns 中的代码试图避免对隐藏列进行自动调整,但它是在辅助方法 (SetMinWidth ) 被调用,它遍历设置最小宽度的所有列,并且 Width setter 包括将 _hidden 设置为 false 的副作用(如果宽度不为零) ,当使用 AutoFitColumns.

的零参数重载时

如果您使用 AutoFitColumns 的 1 或 2 参数重载传递最小宽度为零,列将保持隐藏状态,但您的空列将是零宽度,所以它不是确实是一个解决方法。

这是我目前用作解决方法的扩展方法:

static void AutoFitColumnsAndRehide(this ExcelRangeBase range)
{
    range.Reset();

    var hiddenColumns = range
        .Select(cell => cell.Start.Column)
        .Distinct()
        .Select(range.Worksheet.Column)
        .Where(column => column.Hidden)
        .ToList();

    range.AutoFitColumns();

    foreach (var column in hiddenColumns)
    {
        column.Hidden = true;
    }
}

这显然也可以针对 1 参数和 2 参数重载进行调整。