Autofit Row Height of Merged Cell in EPPlus

匿名 (未验证) 提交于 2019-12-03 02:33:02

问题:

I'm using EPPlus and C# and trying to autosize/autofit the height of a row to accommodate the height needed to show all of the contents of a merged cell with text wrapping. However no matter what I try the text always truncates. Since I'm repeating this process with various text sizes on various worksheets, I don't want to hard code the row height (except to enforce a minimum height for the row). If possible I'd like to do this within EPPlus/C#.

With the cells A2:E2 merged and WrapText = true:

Cell with Text Truncated

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

Here's my relevant and short C# code

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; } 

I've looked at Autofit rows in EPPlus and it didn't seem to directly answer my question unless I'm reading it wrong.

回答1:

Here is the solution in a reusable method. Pass in the text value, font used for the cell, summed width of the columns merged, and receive back the row height. Set the row height with the result.

Use of Method

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

Reuseable Method

    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);     } 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!