2017-07-19 47 views
1

我正在使用c#Excel Interop并试图使合并单元格的高度适合其内容。在合并单元格自动调整不能出于某种原因做,所以我用下面的方法Excel - 列宽不匹配多个加起来

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最终会稍微变小,导致内容有时会再次回绕,并为合并的单元格分配太多空间。

这也发生在excel中,当你将两个或更多的列宽相加并将它分配给单元格为宽度时,它最终会稍微变小。
单元格是否具有某种填充/边距,我该如何考虑?

回答

0

弄成宽度计算后加入以下代码:

// excel has some cell padding or whatever? This is a workaround for it 
width += .514 * ((toMerge.Columns.Count-1) * 2); 

这是一个黑客,但它符合我的需求,并为我工作。它所做的基本上是假定所有具有特定值的单元格都有一些填充并将其添加到总数中。

不接受这个作为答案,因为好,事实并非如此。