问题
I have a column in my Excel spreadsheet whose contents I spread (merge) over four rows like so:
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;
}
I later Autofit the columns to be just wide enough to show all content:
_xlSheet.Columns.AutoFit();
The problem is that if there is just one or a few "outliers" among the merged content that is considerably longer than the others, I want to wrap these. How can I, in the case of what I deem excessively long content/text, split that over two lines (because it to wrap)?
I tried adding these:
range.ColumnWidth = 144;
range.WrapText = true;
...so that the code was then:
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;
}
...but this fix fixes nothing.
How do you tell it at what point to wrap the text?
回答1:
Setting WrapText to true for a range does work, in a way - when you manually reduce the width of the column, the text wraps (but only then).
What worked for me was a combination of that word wrapping, and a taking back of the AutoFitting of one column by specifying a precise width for it after calling 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;
来源:https://stackoverflow.com/questions/33677137/how-to-wrap-merged-excel-content-beyond-a-specified-length