我正在使用c#Excel Interop并尝试使合并单元格的高度适合其内容。合并单元格的自动调整由于某种原因无法完成,所以我使用以下方法
private void AutoFitAndMerge(Range toMerge, Range contentCell) {
// Get Width of entire Merged Cell
double width = 0.0;
foreach (Range col in toMerge.Columns) {
width += col.ColumnWidth;
}
// mimic merged cell with regular cell
var cellWidth = contentCell.ColumnWidth;
contentCell.ColumnWidth = width;
contentCell.WrapText = true;
// autofit the regular cell and copy that to merged
contentCell.Rows.AutoFit();
var wantedHeight = contentCell.RowHeight;
// set it back
contentCell.ColumnWidth = cellWidth;
toMerge.Merge();
toMerge.WrapText = true;
toMerge.RowHeight = wantedHeight;
}
除了在开始时,当我将contentCell的宽度设置为合并的单元格总宽度时,它的工作正常。它没有正确加起来。
问题是contentCell最终会略微变小,导致内容有时再次环绕,并为合并的单元格分配太多空间。
当您添加2个或更多列宽并将其作为宽度分配给单元格时,excel中也会发生这种情况,最终会略小一些。 单元格是否具有某种填充/边距,如何将其考虑在内?
答案 0 :(得分:0)
结束宽度计算后添加以下代码:
// excel has some cell padding or whatever? This is a workaround for it
width += .514 * ((toMerge.Columns.Count-1) * 2);
这是一个黑客,但它符合我的要求,并为我工作。它所做的基本上是假设在某个值的所有单元格上都有一个填充,并将其添加到总数中。
不接受这个作为答案,因为它不是。