NPOI 列宽自适应 代码示例

//列宽自适应,只对英文和数字有效
for (int i = 0; i <= maxColumn; i++)
{
    sheet.AutoSizeColumn(i);
}
//获取当前列的宽度,然后对比本列的长度,取最大值
for (int columnNum = 0; columnNum <= maxColumn; columnNum++)
{
    int columnWidth = sheet.GetColumnWidth(columnNum) / 256;
    for (int rowNum = 1; rowNum <= sheet.LastRowNum; rowNum++)
    {
        IRow currentRow;
        //当前行未被使用过
        if (sheet.GetRow(rowNum) == null)
        {
            currentRow = sheet.CreateRow(rowNum);
        }
        else 
        {
            currentRow = sheet.GetRow(rowNum);
        }
                            
        if(currentRow.GetCell(columnNum) != null)
        {
            ICell currentCell = currentRow.GetCell(columnNum);
            int length = Encoding.Default.GetBytes(currentCell.ToString()).Length;
            if (columnWidth < length)
            {
                columnWidth = length;
            }
        }
    }
    sheet.SetColumnWidth(columnNum, columnWidth * 256);
}

  

转载于:https://www.cnblogs.com/a14907/p/6424071.html

你可能感兴趣的:(NPOI 列宽自适应 代码示例)