public static void AutoFitColumnWidth(ISheet sheet, int columnCount, int startRowIndex = 0) { for (int ci = 0; ci < columnCount; ci++) { sheet.AutoSizeColumn(ci); } for (int colIndex = 0; colIndex < columnCount; colIndex++) { int columnWidth = sheet.GetColumnWidth(colIndex) / 256; for (int rowNum = startRowIndex; rowNum < sheet.LastRowNum; rowNum++) { IRow currentRow;
if (sheet.GetRow(rowNum) == null) { currentRow = sheet.CreateRow(rowNum); } else { currentRow = sheet.GetRow(rowNum); }
if (currentRow.GetCell(colIndex) != null) { ICell currentCell = currentRow.GetCell(colIndex); int length = Encoding.Default.GetBytes(currentCell.ToString()).Length; if (columnWidth < length) { columnWidth = length; } }
if (columnWidth > 255) { columnWidth = 255; break; } }
sheet.SetColumnWidth(colIndex, columnWidth * 256); } }
|