News Category

C#/VB.NET: AutoFit Column Width and Row Height in Excel

2022-06-01 07:27:00 Written by  support iceblue
Rate this item
(0 votes)

When the text entered in a cell is too long to be fully displayed in the current cell, the “AutoFit” feature in Excel allows you to quickly adjust the column width or row height to fit all the content and make the entire worksheet more readable. In this article, you will learn how to programmatically AutoFit the column width and row height in an Excel worksheet using Spire.XLS for .NET.

Install Spire.XLS for .NET

To begin with, you need to add the DLL files included in the Spire.XLS for .NET package as references in your .NET project. The DLL files can be either downloaded from this link or installed via NuGet.

PM> Install-Package Spire.XLS

AutoFit Column Width and Row Height in Excel

The detailed steps are as follows.

  • Create a Workbook object.
  • Load a sample Excel document using Workbook.LoadFromFile() method.
  • Get a specified worksheet using Workbook.Worksheets[] property.
  • Get the used range on the specified worksheet using Worksheet.AllocatedRange property.
  • AutoFit column width and row height in the range using CellRange.AutoFitColumns() and CellRange.AutoFitRows() methods.
  • Save the result file using Workbook.SaveToFile() method.
  • C#
  • VB.NET
using Spire.Xls;

namespace AutofitColumn
{
    class Program
    {
        static void Main(string[] args)
        {
            //Create a Workbook object
            Workbook workbook = new Workbook();

            //Load a sample Excel document
            workbook.LoadFromFile(@"E:\Files\Test.xlsx");

            //Get the first worksheet
            Worksheet worksheet = workbook.Worksheets[0];

            //AutoFit column width and row height
            worksheet.AllocatedRange.AutoFitColumns();
            worksheet.AllocatedRange.AutoFitRows();

            //Save the result file
            workbook.SaveToFile("AutoFit.xlsx", FileFormat.Version2010);
        }
    }
}

C#/VB.NET: AutoFit Column Width and Row Height in Excel

Apply for a Temporary License

If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.

Additional Info

  • tutorial_title:
Last modified on Wednesday, 01 June 2022 01:30