Autofit Row Height of Merged Cell in EPPlus

后端 未结 3 713
予麋鹿
予麋鹿 2020-12-19 02:41

I\'m using EPPlus and C# and trying to autosize/autofit the height of a row to accommodate the height needed to show all of the contents of a merged cell with text wrapping.

相关标签:
3条回答
  • 2020-12-19 02:52

    Here is the solution in a reusable method. Pass in the text value, font used for the cell, summed width of the columns merged, and receive back the row height. Set the row height with the result.

    Use of Method

    eppWorksheet.Row(2).Height = MeasureTextHeight(cell.Value, cell.Style.Font, [enter the SUM of column widths A-E]);
    

    Reuseable Method

        public double MeasureTextHeight(string text, ExcelFont font, double width)
        {
            if (text.IsNullOrEmpty()) return 0.0;
            var bitmap = _bitmap ?? (_bitmap = new Bitmap(1, 1));
            var graphics = _graphics ?? (_graphics = Graphics.FromImage(bitmap));
    
            var pixelWidth = Convert.ToInt32(width * 7);  //7 pixels per excel column width
            var fontSize = font.Size * 1.01f;
            var drawingFont = new Font(font.Name, fontSize);
            var size = graphics.MeasureString(text, drawingFont, pixelWidth, new StringFormat { FormatFlags = StringFormatFlags.MeasureTrailingSpaces });
    
            //72 DPI and 96 points per inch.  Excel height in points with max of 409 per Excel requirements.
            return Math.Min(Convert.ToDouble(size.Height) * 72 / 96, 409);
        }
    
    0 讨论(0)
  • 2020-12-19 03:03

    Had to tweak the code a little bit by removing the multiplication factor at the return line. May be because i am using this code to get the width of the column.

    ws1.Column(colIndx).Width * 7
    

    The multiplication factor is the number of columns been merged.

    0 讨论(0)
  • 2020-12-19 03:07

    I have used a workaround for this and I a had print area A:Q.

    1. I copied merged cells value to column z.
    2. set width of column z to merge cells width.
    3. Then set auto row height true in format.
    4. Hide the z column.
    5. Set print area A:Q

    Cons: There are duplicate data. But we are okay since report is printing and not print z column.

    Pros: Row height works correctly not like calculation method.

    0 讨论(0)
提交回复
热议问题