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.

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
Excel Row and Column AutoFit Screenshot

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

Upload your file(Drag files here)

Download a sample file

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

class Sample
{
    [STAThread]
    static void Main(string[] args)
    {
        // If using Professional version, put your serial key below.
        SpreadsheetInfo.SetLicense("FREE-LIMITED-KEY");

        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

Module Samples

    Sub Main()

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

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

        ef.Save("Row_Column AutoFit.xlsx")

    End Sub

End Module

Check next sample.