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

我正在使用EPPlus和C#,并试图autosize / autofit行的高度,以适应所需的高度显示合并单元格的所有内容与文字环绕。 不过无论我怎么试试文本总是截断。 由于我在各种工作表上用各种文本大小重复这个过程,所以我不想对行高进行硬编码(除了强制行的最小高度外)。 如果可能的话,我想在EPPlus / C#中执行此操作。

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

与文本截断的单元格

在这里输入图像说明

这是它应该看起来像所希望的单元格高度

在这里输入图像说明

这是我的相关和短的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; } 

我已经看过EPPlus中的Autofit行,除非我读错了,否则它不会直接回答我的问题。

这是一个可重用方法的解决scheme。 传入文本值,用于单元格的字体,合并列的宽度,并接收行高。 用结果设置行高。

方法的使用

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

可重用的方法

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