[英]Autofit Row Height of Merged Cell in EPPlus
我正在使用 EPPlus 和 C# 并尝试自动调整/自动调整行的高度以适应显示带有文本换行的合并单元格的所有内容所需的高度。 但是,无论我尝试什么,文本总是会被截断。 由于我在各种工作表上使用各种文本大小重复此过程,因此我不想对行高进行硬编码(除了强制执行行的最小高度)。 如果可能,我想在 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 行,它似乎没有直接回答我的问题,除非我读错了。
这是可重用方法的解决方案。 传入文本值、单元格使用的字体、合并列的总宽度,并接收行高。 用结果设置行高。
方法的使用
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);
}
我为此使用了一种解决方法,并且我有一个打印区域 A:Q。
缺点:有重复的数据。 但是我们没问题,因为报告正在打印而不是打印 z 列。
优点:行高工作正常,不像计算方法。
不得不通过删除返回行的乘法因子来稍微调整代码。 可能是因为我正在使用此代码来获取列的宽度。
ws1.Column(colIndx).Width * 7
倍增因子是合并的列数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.