要导出一个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); } }