跨行的合并单元格中的文本被截断,因为Excel会在自动调整行的大小时忽略合并的单元格。
如何将单元格高度调整为其内容,以便调整大小的行不起作用?
我发布此信息是为了帮助那些遇到此问题的人。我发布了一个解决方案作为答案。
答案 0 :(得分:2)
对于此解决方案,我只显示与调整不显示数据的行相关的代码
解决方案:
///
/// Merged Row Model Psuedo Code
///
MergedRow {
// Fields merged across rows
...
// list of rows with non merged data
list<indvidulerow> data
}
///
/// Code to find rows with merged cells.
///
... // worksheet prep
var mergedRows = new Dictionary<int, MergedRow>();
... // begin generating rows
...
// code generating the first merged cell of a row
using (var r = sheet.Cells[rowIndex, 1, rowIndex+ mergedRow.Data.Count - 1, 1]){
if(mergedRow.Data.count>1){
r.Merge=true;
mergedRows.Add(rowIndex, mergedRow);
}
... // code for remainder of of cell
///
/// Code to Resize Rows. Making last row expand enough to see
/// all content in merged cells
///
foreach (var firstRowIndex in mergedRows.Keys){
var numRowsMerged = mergedRows[firstRowIndex].Data.Count;
var columnHeights = new List<ColumnHeightCalcModel>();
for (var colIndex = 0; colIndex < totalColumns; colIndex++){
var calcModel = new ColumnHeightCalcModel();
var combinedHeight = 0.0;
var lastRowHeight = 0.0;
for (rowIndex = 0; rowIndex < numRowsMerged; rowIndex++){
var cell = sheet.Cells[firstRowIndex + rowIndex, colIndex + 1];
var cellText = cell.Text;
var cellmerged = cell.Merge;
var cellWidth = sheet.Column(colIndex+1).Width;
var font = cell.Style.Font;
if (string.IsNullOrEmpty(cellText)) combinedHeight += 0.0;
var bitmap =new Bitmap(1,1);
var graphics = Graphics.FromImage(bitmap);
var pixelWidth = Convert.ToInt32(cellWidth * 6.0); //6.0 pixels per excel column width
var drawingFont = new Font(font.Name, font.Size);
var size = graphics.MeasureString(cellText, drawingFont, pixelWidth);
//72 DPI and 96 points per inch. Excel height in points with max of 409 per Excel requirements.
combinedHeight += Math.Min(Convert.ToDouble(size.Height) * 72 / 96, 409);
if (cellmerged) break;
lastRowHeight = Math.Min(Convert.ToDouble(size.Height) * 72 / 96, 409);
}
calcModel.TotalCombinedHeight = combinedHeight;
calcModel.LastRowHeight = lastRowHeight;
columnHeights.Add(calcModel);
}
var row = sheet.Row(firstRowIndex + numRowsMerged - 1);
row.CustomHeight = true;
var maxCombo = columnHeights.Max(col => col.TotalCombinedHeight);
var maxLast = columnHeights.Max(col => col.LastRowHeight);
row.Height = maxCombo - maxLast;
}
结束解决方案
帮助我找到此解决方案的链接
以下链接适用于合并列,但它有助于合并行。