c# - EPPlus中合并单元格的自动调整行高

标签 c# excel epplus

我正在使用 EPPlus 和 C# 并尝试自动调整行高/自动调整行高以适应显示具有文本换行的合并单元格的所有内容所需的高度。但是,无论我尝试什么,文本总是会被截断。由于我在各种工作表上使用各种文本大小重复此过程,因此我不想对行高进行硬编码(除非强制执行行的最小高度)。如果可能,我想在 EPPlus/C# 中执行此操作。

合并单元格 A2:E2 且 WrapText = true:

文本被截断的单元格

enter image description here

这是具有所需单元格高度的外观

enter image description here

这是我相关的简短 C# 代码

Int32 intToCol;
intToCol = 5;
eppWorksheet.Cells[2, 1, 2, intToCol].Merge = true;
eppWorksheet.Cells[2, 1].Style.WrapText = true; 
//Check if at the minimum height. If not, resize the row
if (eppWorksheet.Row(2).Height < 35.25)
{
    eppWorksheet.Row(2).Height = 35.25;
}

我看过Autofit rows in EPPlus除非我读错了,否则它似乎没有直接回答我的问题。

最佳答案

这是可重用方法中的解决方案。传入文本值、单元格使用的字体、合并列的总宽度,并接收回行高。用结果设置行高。

方法的使用

eppWorksheet.Row(2).Height = MeasureTextHeight(cell.Value, cell.Style.Font, [enter the SUM of column widths A-E]);

可重复使用的方法

    public double MeasureTextHeight(string text, ExcelFont font, double width)
    {
        if (text.IsNullOrEmpty()) return 0.0;
        var bitmap = _bitmap ?? (_bitmap = new Bitmap(1, 1));
        var graphics = _graphics ?? (_graphics = Graphics.FromImage(bitmap));

        var pixelWidth = Convert.ToInt32(width * 7);  //7 pixels per excel column width
        var fontSize = font.Size * 1.01f;
        var drawingFont = new Font(font.Name, fontSize);
        var size = graphics.MeasureString(text, drawingFont, pixelWidth, new StringFormat { FormatFlags = StringFormatFlags.MeasureTrailingSpaces });

        //72 DPI and 96 points per inch.  Excel height in points with max of 409 per Excel requirements.
        return Math.Min(Convert.ToDouble(size.Height) * 72 / 96, 409);
    }

关于c# - EPPlus中合并单元格的自动调整行高,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41639278/

相关文章:

C# EPPLUS Chart SetPosition 方法行偏移不起作用

c# - Mini Profiler 与 SqlConnection 集成

c# - 必须实现通用的小于和大于操作

Excel 上的 VBA 应用程序

vba - 创建图表时的 Excel 变量范围

c# - 使用 EPplus 向 Excel 添加文本

c# - 您如何看待在 C# 中使用属性作为对象初始值设定项?

c# - 空引用异常 : unity3d

vba - 如何在从 Excel 传递参数的同时执行批处理文件

excel - 从 Excel 单元格读取