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

See the full code below, use Run Example to execute.

Upload your file(Drag files here)

Download an input file

using System;
using System.Collections.Generic;
using System.Text;
using GemBox.Spreadsheet;
using GemBox.Spreadsheet.ConditionalFormatting;
using GemBox.Spreadsheet.PivotTables;
using GemBox.Spreadsheet.Tables;

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

        ExcelFile ef = ExcelFile.Load("SimpleTemplate.xlsx");

        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.xlsx");
Imports System
Imports System.Collections.Generic
Imports System.Text
Imports GemBox.Spreadsheet
Imports GemBox.Spreadsheet.ConditionalFormatting
Imports GemBox.Spreadsheet.PivotTables
Imports GemBox.Spreadsheet.Tables

Module Samples

    Sub Main()

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

        Dim ef As ExcelFile = ExcelFile.Load("SimpleTemplate.xlsx")

        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.xlsx")

    End Sub

End Module