1. 程式人生 > >NOPI建立Excel後中文單元格的列寬自適應

NOPI建立Excel後中文單元格的列寬自適應

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+3; //+3是為了美觀
                            }
                        }
                    }
                    sheet.SetColumnWidth(columnNum, columnWidth * 256);
                }