NPOI自适应列宽

当本地没有安装Excel,但是又想导出Excel,采用Office插件是行不通的,NPOI是导出Excel的一个开源的插件。在导出Excel后,为了方便阅读,可以才采用自适应列宽的方式使得单元格的宽度和文本的宽度接近。NPOI中工作簿ISheet有自适应列宽的方法,但是其效果列宽还是比单元中文字的宽度稍微大一点。此时我们可以自己计算其宽度,自定义列宽。一下这种方式是支持中英文以及数字的。

 public void AutoColumnWidth(ISheet sheet,int cols)
        {
            for (int col = 0; col <= cols; col++)
            {
                sheet.AutoSizeColumn(col);//自适应宽度,但是其实还是比实际文本要宽
                int columnWidth = sheet.GetColumnWidth(col) / 256;//获取当前列宽度
                for (int rowIndex = 1; rowIndex <= sheet.LastRowNum; rowIndex++)
                {
                    IRow row = sheet.GetRow(rowIndex);
                    ICell cell = row.GetCell(col);
                    int contextLength = Encoding.UTF8.GetBytes(cell.ToString()).Length;//获取当前单元格的内容宽度
                    columnWidth = columnWidth < contextLength ? contextLength : columnWidth;

                }
                sheet.SetColumnWidth(col, columnWidth * 200);//

            }
        }
 sheet.SetColumnWidth(col, columnWidth * 200);//  经过测试200比较合适。
原文地址:https://www.cnblogs.com/hglSV/p/10223214.html