在 NPOI.HSSF.UserModel.HSSFSheet.SetColumnWidth(Int32 column, Int32 width) ↵

 #region 设置自适应宽度(支持中文)
        /// <summary>
        /// 设置自适应宽度(支持中文)
        /// </summary>
        /// <param name="sheet">对象页</param>
        /// <param name="columnCount">列总数</param>
        /// <returns></returns>
        public static ISheet AutoSetWidth(ISheet sheet, int columnCount)
        {

            //获取当前列的宽度,然后对比本列的长度,取最大值
            for (int columnNum = 0; columnNum <= columnCount; columnNum++)
            {
                //sheet.SetColumnWidth(columnNum, 256);
                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 + 3; //+3为了美观
                        }
                    }
                }
                if (columnWidth > 255)
                    columnWidth = 254;
                sheet.SetColumnWidth(columnNum, columnWidth * 256);


            }

            return sheet;
        }
        #endregion

上面代码是设置表格自适应宽度,

解决这个问题只用设置一下相应列的宽度(宽度不可超过255,不会影响内容)即可,当然调用上面这个方法也行。

sheet.SetColumnWidth(columnNum, columnWidth * 256);。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

雨中深巷的油纸伞

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值