首页 文章

在EPPlus中自动调整合并单元格的行高

提问于
浏览
5

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

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

Cell with Text Truncated

enter image description here

Here's what it should look like with desired Cell Height

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并没有读错了.2646072_读错了 .

1 回答

  • 16

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

    使用方法

    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, int width)
        {
            if (string.IsNullOrEmpty(text)) return 0.0;
            var bitmap = new Bitmap(1, 1);
            var graphics = Graphics.FromImage(bitmap);
    
            var pixelWidth = Convert.ToInt32(width * 7.5);  //7.5 pixels per excel column width
            var drawingFont = new Font(font.Name, font.Size);
            var size = graphics.MeasureString(text, drawingFont, pixelWidth);
    
            //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);
        }
    

相关问题