包含包含文本的合并单元格的行的自动高度

时间:2015-11-20 16:24:20

标签: c# export-to-excel closedxml

使用ClosedXML库生成Excel文件时遇到以下问题:包含带有包装文本的合并单元格的行。

我不能责怪这个库,因为在尝试手动执行autoheight时也会发生问题(双击行分隔符)。

2 个答案:

答案 0 :(得分:1)

我发现此问题的解决方案如下:从非合并列中工作表的已定义打印区域外的合并单元格中复制数据,确保目标列的宽度非常接近合并列宽度为1然后执行自动调整。

代码如下所示:

private Dictionary<int, IList<int>> _RowAutofitBufferToMergedColsMapping = new Dictionary<int, IList<int>>();

// tells the exporter what column to use as a buffer
public void RegisterAutofitMapping(int startCol, int stopCol, int bufferCol)
{
  var mergedCols = Enumerable.Range(startCol, stopCol - startCol + 1).ToList();

   if (_RowAutofitBufferToMergedColsMapping.ContainsKey(bufferCol))
      throw new ArgumentException(String.Format("Current worksheet already contains a mapping for buffer column {0}", bufferCol));

            _RowAutofitBufferToMergedColsMapping[bufferCol] = mergedCols;
            Worksheet.Column(bufferCol).Width = mergedCols.Sum(item => Worksheet.Column(item).Width + ColumnSeparatorWidth);
}

// performs row autofit 
public void RowAutofit(int rowNo, int startCol, int stopCol, bool merge = true)
{
   // finding mapping to use for autofit
   IList<int> vals = Enumerable.Range(startCol, stopCol - startCol + 1).ToList();
   String valsStr = String.Join(",", vals);
   var mappingKey = _RowAutofitBufferToMergedColsMapping.Keys.FirstOrDefault(key => vals.SequenceEqual(_RowAutofitBufferToMergedColsMapping[key]));
   if (mappingKey == 0)
      throw new ArgumentException(String.Format("Could not mapping for provided columns - {0}", valsStr));

   var range = Worksheet.Worksheet.Range(rowNo, startCol, rowNo, stopCol);
   if (merge)
      range.Merge();

    range.Style.Alignment.SetWrapText();

    if (copyStyles)
       ClosedXmlExporter.CopyStyles(this, this, rowNo, startCol, rowNo, mappingKey, CopyStyleOptions.CopyAll());

    var sourceValue = Worksheet.Cell(rowNo, startCol).Value;
    Worksheet.Cell(rowNo, mappingKey)
      .SetValue(sourceValue)
      .Style.Alignment.SetWrapText(true);

      Worksheet.Column(AutofitDummyCol).AdjustToContents(rowNo, rowNo);
}

Excel tips的启发。

答案 1 :(得分:1)

private void mergeCellAutoFit(Excel.Range range) //range had value
{
     range.HorizontalAlignment = 7;//format center across Selection
     range.WrapText = true;//set wrap text

     double dRowHeight = Convert.ToDouble(range.RowHeight);//get row heigth now
     range.MergeCells = true; //merge cell
     range.EntireRow.RowHeight = dRowHeight; //perfect row heigth
     range.HorizontalAlignment = 2; //align text left
}