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 Row and Column AutoFit Screenshot
Upload your file (Drag file here)
using System;
using GemBox.Spreadsheet;

class Program
    static void Main(string[] args)
        // If using Professional version, put your serial key below.

        ExcelFile ef = ExcelFile.Load("%InputFileName%");

        var ws = ef.Worksheets[0];

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

        ef.Save("Row Column AutoFit.%OutputFileType%");
Imports GemBox.Spreadsheet

Module Program

    Sub Main()

        ' If using Professional version, put your serial key below.

        Dim ef As ExcelFile = ExcelFile.Load("%InputFileName%")

        Dim ws = ef.Worksheets(0)

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

        ef.Save("Row Column AutoFit.%OutputFileType%")

    End Sub

End Module

Check next example or download examples from GitHub.