NPOI 計算單元格高度

需求

要導出一個Excel,第一行是不定長字符串,合併單元格(A-G)已知,現要計算第一行的高度。c#

圖例

思路

已知,NPOI的寬度單位是1/256個英文字符,在本例中,A列的寬度是2048,即 2048 / 256 = 8 個英文字符。在A4單元格里也能夠看出。以下圖:字體

圖例

第一行默認的行高,正好顯示一行文字。我要作的就是,計算出A-G列寬度一行能容納的漢字數量,再根據 「行數 = 總字數 / 一行字數 」 計算出須要的行數,設置 第一行高度 = 原高度 ✖ 行數。this

接下來要解決的問題就是如何計算一行字數的問題了。這裏咱們能夠利用C#的System.Drawing.Graphics裏的MeasureString,分別得到字母的寬度,和漢字的寬度,按比例進行計算。code

固然這個方法也不是絕對準確,但估算出的值對大多數狀況已經夠用了。blog

代碼實現

public void SetRowHight(ISheet sheet, string text)
            {
                var width = 0.0;

                // 計算單元格長度
                for (int i = 1; i <= sheet.GetRow(0).Cells.Count; i++)
                {
                    width += sheet.GetColumnWidth(i);
                }

                // 獲取每行漢字長度
                double length = Util.GetChineseLength(
                    sheet.Workbook.GetFontAt(0),
                    this.cellStyles.TipStyle.GetFont(sheet.Workbook), // 個人漢字字體
                    width);

                sheet.GetRow(0).Height = Convert.ToInt16(sheet.GetRow(0).Height * Math.Ceiling(text.Length / length));
            }

        /// <summary>
        /// 計算可容納漢字數
        /// </summary>
        /// <param name="eFont">英文字體</param>
        /// <param name="cFont">中文字體</param>
        /// <param name="length">單元格長度</param>
        /// <returns>可容納漢字數量</returns>
        public static int GetChineseLength(IFont eFont, IFont cFont, double length)
        {
            using (var bitmap = new Bitmap(1, 1))
            {
                var graphics = Graphics.FromImage(bitmap);
                var size1 = graphics.MeasureString("abcdefg", new Font(eFont.FontName, eFont.FontHeightInPoints));
                var size2 = graphics.MeasureString("一二三四五六七", new Font(cFont.FontName, cFont.FontHeightInPoints));
                return (int)Math.Floor((length / 256) * size1.Width / size2.Width);
            }
        }
相關文章
相關標籤/搜索