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.

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

class Program
    static void Main()
        // If using the Professional version, put your serial key below.

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

        var worksheet = workbook.Worksheets.ActiveWorksheet;

        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 the Professional version, put your serial key below.

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

        Dim worksheet = workbook.Worksheets.ActiveWorksheet

        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))

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

See also

Next steps

GemBox.Spreadsheet is a .NET component that enables you to read, write, edit, convert, and print spreadsheet files from your .NET applications using one simple API.

Download Buy