我正在使用 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;
}
我看过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/