我的Excel电子表格中有一列,其内容我传播(合并)四行,如下所示:
private void AddDescription(String desc)
{
int curDescriptionBottomRow = _curDescriptionTopRow + 3;
var range = _xlSheet.Range[_xlSheet.Cells[_curDescriptionTopRow, ITEMDESC_COL], _xlSheet.Cells[curDescriptionBottomRow, ITEMDESC_COL]];
range.Merge();
range.Font.Bold = true;
range.VerticalAlignment = XlVAlign.xlVAlignCenter;
range.Value2 = desc;
}
我后来自动调整列的宽度足以显示所有内容:
_xlSheet.Columns.AutoFit();
问题是,如果合并内容中只有一个或几个“异常值”比其他内容长得多,我想包装它们。在我认为过长的内容/文本的情况下,我怎么能将它分成两行(因为它要换行)?
我尝试添加这些:
range.ColumnWidth = 144;
range.WrapText = true;
...所以代码是:
private void AddDescription(String desc)
{
int curDescriptionBottomRow = _curDescriptionTopRow + 3;
var range = _xlSheet.Range[_xlSheet.Cells[_curDescriptionTopRow, ITEMDESC_COL], _xlSheet.Cells[curDescriptionBottomRow, ITEMDESC_COL]];
range.Merge();
range.Font.Bold = true;
range.ColumnWidth = 42;
range.WrapText = true;
range.VerticalAlignment = XlVAlign.xlVAlignCenter;
range.Value2 = desc;
}
...但是此修复程序没有任何修复。
你如何告诉它在什么时候包装文本?
在某种程度上将WrapText设置为true确实有效 - 当您手动减小列的宽度时,文本将换行(但仅限于此)。
对我有用的是这个自动换行的组合,并通过在调用AutoFit后为其指定精确宽度来收回一列的自动调整:
private static readonly int WIDTH_FOR_ITEM_DESC_COL = 42;
. . .
_xlSheet.Columns.AutoFit();
// The AutoFitting works pretty well, but one column needs to be manually tweaked due to potentially over-long Descriptions
((Range)_xlSheet.Cells[1, 1]).EntireColumn.ColumnWidth = WIDTH_FOR_ITEM_DESC_COL;