Excel Row and Column AutoFit in C# and VB.NET

GemBox.Spreadsheet supports autofitting column width and row height so that column / row takes just enough space to make content of all its cells visible.

Following example shows how to autofit all columns in an Excel worksheet with C# and VB.NET.

Notice the usage of CalculateMaxUsedColumns method to get the total number of columns with a non-empty cells in a worksheet.

Screenshot of Excel columns autofitted with GemBox.Spreadsheet
Excel columns autofitted with GemBox.Spreadsheet
Upload your file (Drag file here)
using GemBox.Spreadsheet;

class Program
{
    static void Main()
    {
        // If using Professional version, put your serial key below.
        SpreadsheetInfo.SetLicense("FREE-LIMITED-KEY");

        var workbook = ExcelFile.Load("%InputFileName%");

        var worksheet = workbook.Worksheets[0];

        int columnCount = worksheet.CalculateMaxUsedColumns();
        for (int i = 0; i < columnCount; i++)
            worksheet.Columns[i].AutoFit(1, worksheet.Rows[1], worksheet.Rows[worksheet.Rows.Count - 1]);

        workbook.Save("Row_Column AutoFit.%OutputFileType%");
    }
}
Imports GemBox.Spreadsheet

Module Program

    Sub Main()

        ' If using Professional version, put your serial key below.
        SpreadsheetInfo.SetLicense("FREE-LIMITED-KEY")

        Dim workbook = ExcelFile.Load("%InputFileName%")

        Dim worksheet = workbook.Worksheets(0)

        Dim columnCount = worksheet.CalculateMaxUsedColumns()
        For i As Integer = 0 To columnCount - 1
            worksheet.Columns(i).AutoFit(1, worksheet.Rows(1), worksheet.Rows(worksheet.Rows.Count - 1))
        Next

        workbook.Save("Row_Column AutoFit.%OutputFileType%")
    End Sub
End Module

Check next example or download examples from GitHub.