Skip to main content

How to AutoFit Excel Row Height and Column Width in C#

 When generating or processing Excel files programmatically, it is common to encounter layout issues. For example, long text may be cut off because the column is too narrow, wrapped text may not be fully visible, or exported data may look uneven after being written in bulk.

For a single Excel file, you can manually adjust the layout in Microsoft Excel by double-clicking the row or column border. However, in scenarios such as report generation, data export, or batch file processing, it is more practical to adjust row heights and column widths automatically through code.

This article shows how to auto fit row height and column width in Excel using C#. The examples cover the following scenarios:

  • Auto fit all used rows and columns in a worksheet

  • Auto fit a specific column

  • Auto fit a specific row

  • Auto fit a specific cell range


Preparation

This article uses Free Spire.XLS for .NET to work with Excel files in C#. You can install it through NuGet:

Install-Package FreeSpire.XLS

Then include the following namespace in your code:

using Spire.Xls;

The examples use the following Excel file path:

E:\Files\Test.xlsx

You can replace it with your own file path as needed.

Auto Fit All Rows and Columns in an Excel Worksheet

If you want the data in a worksheet to be displayed as completely as possible, you can get the used range of the worksheet and call the AutoFitColumns() and AutoFitRows() methods.

using Spire.Xls;

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

            // Load an Excel file
            workbook.LoadFromFile(@"E:\Files\Test.xlsx");

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

            // Auto fit columns in the used range
            worksheet.AllocatedRange.AutoFitColumns();

            // Auto fit rows in the used range
            worksheet.AllocatedRange.AutoFitRows();

            // Save the result file
            workbook.SaveToFile(@"E:\Files\AutoFit.xlsx", FileFormat.Version2010);

            workbook.Dispose();
        }
    }
}

Here, AllocatedRange refers to the actual used range in the worksheet. Compared with processing the entire worksheet, this approach is more suitable for common data tables and avoids unnecessary operations on blank areas.

Auto Fit a Specific Column in Excel

In some worksheets, you may not need to adjust every column. Instead, you may only need to adjust columns that contain longer text, such as product names, customer names, addresses, or remarks.

The following example shows how to auto fit the width of the first column:

using Spire.Xls;

namespace AutoFitSpecificColumn
{
    class Program
    {
        static void Main(string[] args)
        {
            Workbook workbook = new Workbook();
            workbook.LoadFromFile(@"E:\Files\Test.xlsx");

            Worksheet worksheet = workbook.Worksheets[0];

            // Auto fit the first column
            // Note: The column index starts from 1
            worksheet.AutoFitColumn(1);

            workbook.SaveToFile(@"E:\Files\AutoFitColumn.xlsx", FileFormat.Version2010);

            workbook.Dispose();
        }
    }
}

If you need to auto fit multiple columns, you can use a loop:

// Auto fit columns from 1 to 3
for (int i = 1; i <= 3; i++)
{
    worksheet.AutoFitColumn(i);
}

This approach is useful when a worksheet has many columns, but only some fields require automatic width adjustment.

Auto Fit a Specific Row in Excel

When cells contain wrapped text, large font sizes, or imported content of different lengths, the row height may not be enough to display all content. In this case, you can auto fit only the row that needs adjustment.

The following example shows how to auto fit the height of the first row:

using Spire.Xls;

namespace AutoFitSpecificRow
{
    class Program
    {
        static void Main(string[] args)
        {
            Workbook workbook = new Workbook();
            workbook.LoadFromFile(@"E:\Files\Test.xlsx");

            Worksheet worksheet = workbook.Worksheets[0];

            // Auto fit the first row
            // Note: The row index starts from 1
            worksheet.AutoFitRow(1);

            workbook.SaveToFile(@"E:\Files\AutoFitRow.xlsx", FileFormat.Version2010);

            workbook.Dispose();
        }
    }
}

If you need to auto fit multiple rows, you can also use a loop:

// Auto fit rows from 1 to 10
for (int i = 1; i <= 10; i++)
{
    worksheet.AutoFitRow(i);
}

This method is suitable for title rows, description rows, or data rows with variable content length.

Auto Fit a Specific Cell Range in Excel

In real-world Excel files, you may not want to adjust the entire worksheet. For example, a worksheet may contain a report title, notes, a data table, and a signature area. In this case, you can auto fit only a specific range.

The following example auto fits the row height and column width in the range A1:D10:

using Spire.Xls;

namespace AutoFitRange
{
    class Program
    {
        static void Main(string[] args)
        {
            Workbook workbook = new Workbook();
            workbook.LoadFromFile(@"E:\Files\Test.xlsx");

            Worksheet worksheet = workbook.Worksheets[0];

            // Get a specific cell range
            CellRange range = worksheet.Range["A1:D10"];

            // Auto fit columns in the range
            range.AutoFitColumns();

            // Auto fit rows in the range
            range.AutoFitRows();

            workbook.SaveToFile(@"E:\Files\AutoFitRange.xlsx", FileFormat.Version2010);

            workbook.Dispose();
        }
    }
}

This approach is especially useful for report templates. For example, you can adjust only the data table area without affecting the title, header notes, or footer remarks.

Notes and Best Practices

Auto fitting row height and column width is mainly calculated based on the content inside cells. In practice, the following points are worth noting.

1. Enable Text Wrapping When Needed

If cells contain long text or multiple lines of text, you can enable text wrapping before calling AutoFitRows().

// Enable text wrapping for the used range
worksheet.AllocatedRange.IsWrapText = true;

// Auto fit row height based on the wrapped content
worksheet.AllocatedRange.AutoFitRows();

However, IsWrapText = true changes how text is displayed in cells. If you want to preserve the original layout of a template, avoid applying it to the entire worksheet. Instead, apply it only to the required range:

CellRange range = worksheet.Range["A1:D10"];
range.IsWrapText = true;
range.AutoFitRows();

2. Be Careful with Merged Cells

If a worksheet contains merged cells, the auto fit result may be different from that of normal cells, especially when text spans multiple columns. For such areas, you may need to check the output file and manually set row height or column width if necessary.

3. Avoid Processing Blank Areas

Auto fitting usually has little effect on empty cells. For better efficiency, it is recommended to apply auto fitting to the used range or a specific data range instead of the entire worksheet.

4. Consider Performance for Large Workbooks

For large workbooks, auto fitting a wide range of cells may add extra processing time. If only certain rows, columns, or ranges need adjustment, apply auto fitting only to those areas.

Conclusion

Auto fitting row height and column width is a common requirement when creating or processing Excel files in C#. For regular data tables, you can call AutoFitColumns() and AutoFitRows() on the worksheet’s used range. For more complex worksheets, you can apply auto fitting only to specific rows, columns, or cell ranges.

By using these methods properly, you can make generated Excel files easier to read and reduce the need for manual layout adjustments after export.

Comments

Popular posts from this blog

3 Ways to Generate Word Documents from Templates in Java

A template is a document with pre-applied formatting like styles, tabs, line spacing and so on. You can quickly generate a batch of documents with the same structure based on the template. In this article, I am going to show you the different ways to generate Word documents from templates programmatically in Java using Free Spire.Doc for Java library. Prerequisite First of all, you need to add needed dependencies for including Free Spire.Doc for Java into your Java project. There are two ways to do that. If you use maven, you need to add the following code to your project’s pom.xml file. <repositories>               <repository>                   <id>com.e-iceblue</id>                   <name>e-iceblue</name>...

Insert and Extract OLE objects in Word in Java

You can use OLE (Object Linking and Embedding) to include content from other programs, such as another Word document, an Excel or PowerPoint document to an existing Word document. This article demonstrates how to insert and extract embedded OLE objects in a Word document in Java by using Free Spire.Doc for Java API.   Add dependencies First of all, you need to add needed dependencies for including Free Spire.Doc for Java into your Java project. There are two ways to do that. If you use maven, you need to add the following code to your project’s pom.xml file.     <repositories>               <repository>                   <id>com.e-iceblue</id>                   <name>e-iceblue</name>    ...

Simple Java Code to Convert Excel to PDF in Java

This article demonstrates a simple solution to convert an Excel file to PDF in Java by using free Excel API – Free Spire.XLS for Java . The following examples illustrate two possibilities to convert Excel to PDF:      Convert the whole Excel file to PDF     Convert a particular Excel Worksheet to PDF Before start with coding, you need to Download Free Spire.XLS for Java package , unzip it and import Spire.Xls.jar file from the lib folder in your project as a denpendency. 1. Convert the whole Excel file to PDF Spire.XLS for Java provides saveToFile method in Workbook class that enables us to easily save a whole Excel file to PDF. import com.spire.xls.FileFormat; import com.spire.xls.Workbook; public class ExcelToPDF {     public static void main(String[] args){         //Create a Workbook         Workbook workbook = new Workbook();   ...