Comment ajuster automatiquement les lignes et colonnes dans Excel | IronXL

How to Auto Resize Rows and Columns

This article was translated from English: Does it need improvement?
Translated
View the article in English

Resizing rows and columns in a spreadsheet can save a lot of space and make it more readable. The IronXL C# library provides the functionality to automatically resize rows and columns. Since it is done in C#, the resize methods can be called for all the existing rows and columns, automating the manual task in the spreadsheet.

Quickstart: Auto-Resize a Column or Row with a Single Call

With IronXL, you can resize any row or column in just one line—no Interop, no fuss. Use WorkSheet.AutoSizeColumn(int, bool) or WorkSheet.AutoSizeRow(int, bool) to instantly adjust dimensions based on cell content (merged cells optional).

Nuget IconGet started making PDFs with NuGet now:

  1. Install IronXL with NuGet Package Manager

    PM > Install-Package IronXL.Excel

  2. Copy and run this code snippet.

    // One-line: auto-resize column A including merged cells
    workSheet.AutoSizeColumn(0, true);
    // Or auto-resize row 5 quickly
    workSheet.AutoSizeRow(4, true);
  3. Deploy to test on your live environment

    Start using IronXL in your project today with a free trial
    arrow pointer

Auto Resize Rows Example

The AutoSizeRow method automatically resizes the height of a specified row(s) based on its content.

:path=/static-assets/excel/content-code-examples/how-to/autosize-rows-columns-rows.cs
using IronXL;

// Load existing spreadsheet
WorkBook workBook = WorkBook.Load("sample.xlsx");
WorkSheet workSheet = workBook.DefaultWorkSheet;

// Apply auto resize on row 2
workSheet.AutoSizeRow(1);

workBook.SaveAs("autoResize.xlsx");
Imports IronXL

' Load existing spreadsheet
Private workBook As WorkBook = WorkBook.Load("sample.xlsx")
Private workSheet As WorkSheet = workBook.DefaultWorkSheet

' Apply auto resize on row 2
workSheet.AutoSizeRow(1)

workBook.SaveAs("autoResize.xlsx")
$vbLabelText   $csharpLabel

Demonstration

Auto Resize Row

Auto Resize Columns Example

Use the AutoSizeColumn method to resize the width of column(s) based on its content length.

:path=/static-assets/excel/content-code-examples/how-to/autosize-rows-columns-columns.cs
using IronXL;

// Load existing spreadsheet
WorkBook workBook = WorkBook.Load("sample.xlsx");
WorkSheet workSheet = workBook.DefaultWorkSheet;

// Apply auto resize on column A
workSheet.AutoSizeColumn(0);

workBook.SaveAs("autoResizeColumn.xlsx");
Imports IronXL

' Load existing spreadsheet
Private workBook As WorkBook = WorkBook.Load("sample.xlsx")
Private workSheet As WorkSheet = workBook.DefaultWorkSheet

' Apply auto resize on column A
workSheet.AutoSizeColumn(0)

workBook.SaveAs("autoResizeColumn.xlsx")
$vbLabelText   $csharpLabel

Demonstration

Auto Resize Column

ConseilsAll row and column index positions follow zero-based indexing.


Advanced Auto Resize Rows Example

Another overload of the AutoSizeRow method takes a second parameter as a Boolean value. This parameter lets you consider the merged cells when resizing.

:path=/static-assets/excel/content-code-examples/how-to/autosize-rows-columns-advance-rows.cs
using IronXL;

// Load existing spreadsheet
WorkBook workBook = WorkBook.Load("sample.xlsx");
WorkSheet workSheet = workBook.DefaultWorkSheet;

// Apply auto resize to rows individually
workSheet.AutoSizeRow(0, true);
workSheet.AutoSizeRow(1, true);
workSheet.AutoSizeRow(2, true);

workBook.SaveAs("advanceAutoResizeRow.xlsx");
Imports IronXL

' Load existing spreadsheet
Private workBook As WorkBook = WorkBook.Load("sample.xlsx")
Private workSheet As WorkSheet = workBook.DefaultWorkSheet

' Apply auto resize to rows individually
workSheet.AutoSizeRow(0, True)
workSheet.AutoSizeRow(1, True)
workSheet.AutoSizeRow(2, True)

workBook.SaveAs("advanceAutoResizeRow.xlsx")
$vbLabelText   $csharpLabel

Example

For instance, suppose the content has a height of 192 pixels and is located in a merged region that spans 3 rows. When applying auto resize to any of these rows, the algorithm divides the content's height of 192 px by 3, resulting in a height of 64 px for each row. Remember that the AutoSizeRow method needs to be applied to each row individually.

Advance Auto Resize Row

What if the value is set to false?

When the value is set to false, the AutoSizeRow method will adjust the row height based on the content of the cell with the highest height. In Microsoft Excel, when a range of cells is merged, it retains only the value of the upper-left cell and clears the rest. However, with IronXL, the Merge operation is performed without erasing the values of other cells in the merged region.

:path=/static-assets/excel/content-code-examples/how-to/autosize-rows-columns-advance-rows-false.cs
using IronXL;

workSheet.Merge("A1:A3");

workSheet.AutoSizeRow(0, false);
workSheet.AutoSizeRow(1, false);
workSheet.AutoSizeRow(2, false);
Imports IronXL

workSheet.Merge("A1:A3")

workSheet.AutoSizeRow(0, False)
workSheet.AutoSizeRow(1, False)
workSheet.AutoSizeRow(2, False)
$vbLabelText   $csharpLabel
Advance Auto Resize Row

For demonstration purposes, I manually adjusted the row height instead of using the Excel autofit row height function. This was done to avoid adding noticeable top and bottom padding.

With the useMergedCells parameter set to false, the height of merged cells is not being taken into consideration. As a result, there are no changes in height, and each row's height is calculated solely based on its content.

Advanced Auto Resize Columns Example

Similar to AutoSizeRow, you can also make the resizing of columns consider the width of merged cells. When set to true, the width of merged cells will be taken into account. If the merged cell has the longest content, the width of the resized column will be the merged cell's width divided by the number of columns in the merged region.

:path=/static-assets/excel/content-code-examples/how-to/autosize-rows-columns-advance-columns.cs
using IronXL;

// Load existing spreadsheet
WorkBook workBook = WorkBook.Load("sample.xlsx");
WorkSheet workSheet = workBook.DefaultWorkSheet;

// Apply auto resize to columns individually
workSheet.AutoSizeColumn(0, true);
workSheet.AutoSizeColumn(1, true);
workSheet.AutoSizeColumn(2, true);

workBook.SaveAs("advanceAutoResizeColumn.xlsx");
Imports IronXL

' Load existing spreadsheet
Private workBook As WorkBook = WorkBook.Load("sample.xlsx")
Private workSheet As WorkSheet = workBook.DefaultWorkSheet

' Apply auto resize to columns individually
workSheet.AutoSizeColumn(0, True)
workSheet.AutoSizeColumn(1, True)
workSheet.AutoSizeColumn(2, True)

workBook.SaveAs("advanceAutoResizeColumn.xlsx")
$vbLabelText   $csharpLabel

Example

For instance, if the content has a width of 117 pixels and is located in a merged region that spans 2 columns, applying auto resize on any of these columns will result in the width of 59 pixels for each column. The AutoSizeColumn method needs to be applied to each column individually.

Advance Auto Resize Column

What if the value is set to false?

When the value is set to false, the AutoSizeColumn method adjusts the width based on the cell's content with the longest width. In Microsoft Excel, when a range of cells is merged, it keeps only the upper-left value and erases the rest. However, the IronXL Merge method does NOT erase the value of other cells in the merged region.

:path=/static-assets/excel/content-code-examples/how-to/autosize-rows-columns-advance-columns-false.cs
workSheet.Merge("A1:B1");

workSheet.AutoSizeColumn(0, false);
workSheet.AutoSizeColumn(1, false);
workSheet.Merge("A1:B1")

workSheet.AutoSizeColumn(0, False)
workSheet.AutoSizeColumn(1, False)
$vbLabelText   $csharpLabel
Advance Auto Resize Column

The width of merged cells was not being prioritized, resulting in no changes in width because each column's width was calculated based on its content width.

The Differences between Excel and IronXL Auto Resize

Rows

The Excel autofit row height function applies a noticeable top and bottom padding to the cell.

Excel and IronXL Auto Resize Row comparison

Columns

The Excel autofit column width function also applies a left and right padding to the cell, but it is less noticeable.

Excel and IronXL Auto Resize Column comparison

Manual Resizing of Height and Width Example

In addition to relying on the AutoSizeRow and AutoSizeColumn methods to calculate and adjust the width and height of the content, you also have the flexibility to manually adjust the width and height of columns and rows to meet your specific requirements. This allows you to set them to a certain value that suits your needs.

  • Adjust the height: set the Height property of the RangeRow.
  • Adjust the width: set the Width property of the RangeColumn.
:path=/static-assets/excel/content-code-examples/how-to/autosize-rows-columns-manual.cs
using IronXL;

// Load existing spreadsheet
WorkBook workBook = WorkBook.Load("sample.xlsx");
WorkSheet workSheet = workBook.DefaultWorkSheet;

RangeRow row = workSheet.GetRow(0);
row.Height = 10; // Set height

RangeColumn col = workSheet.GetColumn(0);
col.Width = 10; // Set width

workBook.SaveAs("manualHeightAndWidth.xlsx");
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

Height and Width Units in Excel

The measurement units for height and width in Excel differ from each other. Specifically, the height is measured in 1/20 of a point, while the width is determined based on the number of "0"s that can fit in a cell using the font specified in the "Normal" style.

To simplify the conversion of units, let's interpret the value in IronXL, which corresponds to the display pixels in Microsoft Excel. It is important to note that a pixel does not represent a physical point on the screen; rather, it is defined as 1/96 of an inch, regardless of the screen's actual resolution. Excel itself is designed to be resolution-independent and does not rely on physical pixels.

To establish a relationship between IronXL and Excel's height and width measurements, you can consider the following approximations:

  • Height: RangeRow.Height = 10 will result in an approximate height of 1 pixel.
  • Width: RangeColumn.Width = 23.255 will correspond to 1 pixel.

Questions Fréquemment Posées

Comment puis-je ajuster automatiquement les lignes dans Excel en utilisant C# ?

Vous pouvez utiliser la méthode AutoSizeRow dans IronXL pour ajuster automatiquement la hauteur des lignes en fonction de leur contenu dans une feuille Excel.

Quelle est la méthode pour ajuster automatiquement les colonnes dans une feuille Excel ?

IronXL offre la méthode AutoSizeColumn, qui permet l'ajustement automatique des largeurs de colonne en fonction du contenu.

Comment puis-je m'assurer que les cellules fusionnées sont correctement redimensionnées dans Excel ?

IronXL prend en charge le redimensionnement des cellules fusionnées en utilisant un paramètre booléen dans les méthodes AutoSizeRow et AutoSizeColumn pour prendre en compte les cellules fusionnées lors du redimensionnement.

Quels avantages IronXL offre-t-il par rapport aux fonctions d'ajustement automatique natives d'Excel ?

IronXL offre un contrôle précis des dimensions des cellules sans le remplissage supplémentaire que les fonctions d'ajustement automatique natives d'Excel appliquent, permettant ainsi un dimensionnement plus précis des cellules.

Est-il possible de manipuler des fichiers Excel en C# sans Microsoft Office Interop ?

Oui, IronXL vous permet de manipuler des fichiers Excel directement en C# sans dépendre de Microsoft Office Interop, ce qui le rend plus efficace et plus facile à utiliser.

Comment puis-je définir manuellement les tailles de lignes et de colonnes dans un fichier Excel en utilisant C# ?

Vous pouvez définir manuellement la hauteur et la largeur des lignes et des colonnes en ajustant les propriétés Height et Width de RangeRow et RangeColumn dans IronXL.

Quelles unités sont utilisées par IronXL pour définir les hauteurs de ligne et les largeurs de colonne ?

IronXL utilise les unités de mesure par défaut d'Excel, où la hauteur est en 1/20 de point et la largeur est déterminée par le nombre de '0' qui tiennent avec la police dans le style 'Normal'.

IronXL peut-il automatiser le processus de redimensionnement des feuilles Excel ?

Oui, IronXL peut automatiser le redimensionnement des lignes et des colonnes, ce qui améliore la productivité en réduisant le besoin de réglages manuels.

Existe-t-il des ressources disponibles pour apprendre à redimensionner les lignes et les colonnes Excel en utilisant C# ?

Oui, IronXL propose un tutoriel vidéo sur le redimensionnement des lignes et des colonnes, disponible sur YouTube, pour aider les développeurs à apprendre à utiliser ces fonctionnalités.

Pourquoi le redimensionnement automatique est-il important pour les feuilles de calcul Excel ?

Le redimensionnement automatique est crucial pour améliorer la lisibilité et l'esthétique des feuilles de calcul Excel, en s'assurant que tout le contenu est visible et bien présenté sans intervention manuelle.

Chaknith Bin
Ingénieur logiciel
Chaknith travaille sur IronXL et IronBarcode. Il a une expertise approfondie en C# et .NET, aidant à améliorer le logiciel et à soutenir les clients. Ses idées issues des interactions avec les utilisateurs contribuent à de meilleurs produits, documentation et expérience globale.
Prêt à commencer?
Nuget Téléchargements 1,686,155 | Version : 2025.11 vient de sortir