我正在使用 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 中也会发生这种情况,它最终会稍微小一些。
单元格是否有某种填充/边距,我该如何考虑?
最佳答案
最后在宽度计算后添加以下代码:
// excel has some cell padding or whatever? This is a workaround for it
width += .514 * ((toMerge.Columns.Count-1) * 2);
这是一个 hack,但它满足了我的要求并为我工作。它所做的基本上是假设在所有具有特定值的单元格上都有某种填充,并将其添加到总数中。
不接受这个作为答案,因为它不是。
关于c# - Excel - 列宽与多个相加不匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45193831/