Get started with IronXL

Start using IronXL in your project today with a free trial.

First Step:
green 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 an existing spreadsheet
// Note: Ensure that the file "sample.xlsx" exists in the current directory.
WorkBook workBook = WorkBook.Load("sample.xlsx");

// Access the default worksheet in the workbook
WorkSheet workSheet = workBook.DefaultWorkSheet;

// Apply auto-resize on row 1 (index 1 corresponds to the second row in the spreadsheet)
// IronXL uses zero-based indexing for rows, so to access the second row, use index 1.
// If you want to resize multiple rows, you can use a loop or specify additional indexes.
workSheet.AutoSizeRows(1);

// Save the modified workbook as a new file
workBook.SaveAs("autoResize.xlsx");
Imports IronXL



' Load an existing spreadsheet

' Note: Ensure that the file "sample.xlsx" exists in the current directory.

Private workBook As WorkBook = WorkBook.Load("sample.xlsx")



' Access the default worksheet in the workbook

Private workSheet As WorkSheet = workBook.DefaultWorkSheet



' Apply auto-resize on row 1 (index 1 corresponds to the second row in the spreadsheet)

' IronXL uses zero-based indexing for rows, so to access the second row, use index 1.

' If you want to resize multiple rows, you can use a loop or specify additional indexes.

workSheet.AutoSizeRows(1)



' Save the modified workbook as a new file

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;

// This code demonstrates how to load an existing Excel spreadsheet,
// auto-resize the first column (Column A), and save the results
// into a new Excel file.

try
{
    // Load existing spreadsheet
    WorkBook workBook = WorkBook.Load("sample.xlsx");

    // Access the default worksheet in the loaded workbook
    WorkSheet workSheet = workBook.DefaultWorkSheet;

    // Apply auto resize on column A (index 0 corresponds to the first column)
    workSheet.AutoSizeColumn(0);

    // Save the modified workbook with a new file name
    workBook.SaveAs("autoResizeColumn.xlsx");

    Console.WriteLine("Column resized and file saved successfully.");
}
catch(Exception ex)
{
    Console.WriteLine($"An error occurred: {ex.Message}");
}
Imports IronXL



' This code demonstrates how to load an existing Excel spreadsheet,

' auto-resize the first column (Column A), and save the results

' into a new Excel file.



Try

	' Load existing spreadsheet

	Dim workBook As WorkBook = WorkBook.Load("sample.xlsx")



	' Access the default worksheet in the loaded workbook

	Dim workSheet As WorkSheet = workBook.DefaultWorkSheet



	' Apply auto resize on column A (index 0 corresponds to the first column)

	workSheet.AutoSizeColumn(0)



	' Save the modified workbook with a new file name

	workBook.SaveAs("autoResizeColumn.xlsx")



	Console.WriteLine("Column resized and file saved successfully.")

Catch ex As Exception

	Console.WriteLine($"An error occurred: {ex.Message}")

End Try
$vbLabelText   $csharpLabel

Demonstration

Auto Resize Column

Tips
All 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 an existing spreadsheet
WorkBook workBook = WorkBook.Load("sample.xlsx");

// Access the default worksheet within the workbook
WorkSheet workSheet = workBook.DefaultWorkSheet;

// Apply auto resize to individual rows, enabling it for both content and header rows
// The `true` parameter means that the row will resize based on its contents.
// Here, we resize the first three rows of the worksheet to fit the content.
for (int rowIndex = 0; rowIndex <= 2; rowIndex++)
{
    workSheet.AutoSizeRow(rowIndex, true);
}

// Save the modified workbook as a new file
workBook.SaveAs("advanceAutoResizeRow.xlsx");
Imports IronXL



' Load an existing spreadsheet

Private workBook As WorkBook = WorkBook.Load("sample.xlsx")



' Access the default worksheet within the workbook

Private workSheet As WorkSheet = workBook.DefaultWorkSheet



' Apply auto resize to individual rows, enabling it for both content and header rows

' The `true` parameter means that the row will resize based on its contents.

' Here, we resize the first three rows of the worksheet to fit the content.

For rowIndex As Integer = 0 To 2

	workSheet.AutoSizeRow(rowIndex, True)

Next rowIndex



' Save the modified workbook as a new file

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
// Import the IronXL library to work with Excel files
using IronXL;
using System;

// The following code snippet demonstrates how to merge 
// cells and adjust the size of rows in a worksheet.

// NOTE: The code assumes 'workSheet' is a valid instance 
// of a worksheet from a workbook. Proper workbook and 
// worksheet setup are required for execution. Here, we 
// are focusing on the demonstration of merging and resizing cells.

try
{
    // Merge cells from A1 to A3 in the worksheet.
    // This will create a single cell spanning A1 to A3.
    workSheet.Merge("A1:A3");
    
    // Auto-resize the rows in the worksheet.
    // Normally, setting `autoSize` to true allows the row to adjust 
    // based on content. Here, we're demonstrating usage by setting it to false.
    // Rows in IronXL are 0-indexed: Row 0 corresponds to Excel Row 1.
    workSheet.AutoSizeRow(0, false);
    workSheet.AutoSizeRow(1, false);
    workSheet.AutoSizeRow(2, false);
}
catch (Exception ex)
{
    // Handle any exceptions that might occur during the execution
    // and provide meaningful output to understand any issues.
    Console.WriteLine("An error occurred: " + ex.Message);
}
' Import the IronXL library to work with Excel files

Imports IronXL

Imports System



' The following code snippet demonstrates how to merge 

' cells and adjust the size of rows in a worksheet.



' NOTE: The code assumes 'workSheet' is a valid instance 

' of a worksheet from a workbook. Proper workbook and 

' worksheet setup are required for execution. Here, we 

' are focusing on the demonstration of merging and resizing cells.



Try

	' Merge cells from A1 to A3 in the worksheet.

	' This will create a single cell spanning A1 to A3.

	workSheet.Merge("A1:A3")



	' Auto-resize the rows in the worksheet.

	' Normally, setting `autoSize` to true allows the row to adjust 

	' based on content. Here, we're demonstrating usage by setting it to false.

	' Rows in IronXL are 0-indexed: Row 0 corresponds to Excel Row 1.

	workSheet.AutoSizeRow(0, False)

	workSheet.AutoSizeRow(1, False)

	workSheet.AutoSizeRow(2, False)

Catch ex As Exception

	' Handle any exceptions that might occur during the execution

	' and provide meaningful output to understand any issues.

	Console.WriteLine("An error occurred: " & ex.Message)

End Try
$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;

// This code utilizes the IronXL library to manipulate Excel files. Specifically, it loads an existing Excel
// file, applies auto-resizing to specified columns, and saves the updated file.

// Load an existing spreadsheet from the file "sample.xlsx"
WorkBook workBook = WorkBook.Load("sample.xlsx");

// Access the default worksheet of the workbook
WorkSheet workSheet = workBook.DefaultWorkSheet;

// Auto-resize columns to fit their content
// AutoSizeColumn method takes a 0-based column index as its first parameter and whether to ignore header 
// cells in sizing as its second parameter. Here we resize the first three columns.
workSheet.AutoSizeColumn(0, true); // Automatically resize column A
workSheet.AutoSizeColumn(1, true); // Automatically resize column B
workSheet.AutoSizeColumn(2, true); // Automatically resize column C

// Save the workbook with the updated column sizes as "advanceAutoResizeColumn.xlsx"
workBook.SaveAs("advanceAutoResizeColumn.xlsx");
Imports IronXL



' This code utilizes the IronXL library to manipulate Excel files. Specifically, it loads an existing Excel

' file, applies auto-resizing to specified columns, and saves the updated file.



' Load an existing spreadsheet from the file "sample.xlsx"

Private workBook As WorkBook = WorkBook.Load("sample.xlsx")



' Access the default worksheet of the workbook

Private workSheet As WorkSheet = workBook.DefaultWorkSheet



' Auto-resize columns to fit their content

' AutoSizeColumn method takes a 0-based column index as its first parameter and whether to ignore header 

' cells in sizing as its second parameter. Here we resize the first three columns.

workSheet.AutoSizeColumn(0, True) ' Automatically resize column A

workSheet.AutoSizeColumn(1, True) ' Automatically resize column B

workSheet.AutoSizeColumn(2, True) ' Automatically resize column C



' Save the workbook with the updated column sizes as "advanceAutoResizeColumn.xlsx"

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
// Assuming 'workSheet' is an existing object of a worksheet class provided by a library 
// such as EPPlus or a similar spreadsheet manipulation library. 
// The following code demonstrates how to merge cells and auto-size columns effectively.

// Merge cells in the range from A1 to B1.
// Ensure that the method name and its parameters match what is expected by the library being used.
workSheet.Cells["A1:B1"].Merge = true;

// Adjust the column width to fit the content for columns A and B.
// The 'false' parameter usually indicates whether to ignore hidden rows or not.
// Check the specific library documentation to confirm the correct method to use for auto-sizing columns.
workSheet.Column(1).AutoFit();  // Auto-size column A
workSheet.Column(2).AutoFit();  // Auto-size column B

// These operations enhance the worksheet's readability by combining header cells and ensuring data
// is properly visible without manually adjusting widths.
' Assuming 'workSheet' is an existing object of a worksheet class provided by a library 

' such as EPPlus or a similar spreadsheet manipulation library. 

' The following code demonstrates how to merge cells and auto-size columns effectively.



' Merge cells in the range from A1 to B1.

' Ensure that the method name and its parameters match what is expected by the library being used.

workSheet.Cells("A1:B1").Merge = True



' Adjust the column width to fit the content for columns A and B.

' The 'false' parameter usually indicates whether to ignore hidden rows or not.

' Check the specific library documentation to confirm the correct method to use for auto-sizing columns.

workSheet.Column(1).AutoFit() ' Auto-size column A

workSheet.Column(2).AutoFit() ' Auto-size column B



' These operations enhance the worksheet's readability by combining header cells and ensuring data

' is properly visible without manually adjusting widths.
$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;

// This program demonstrates how to load an existing Excel file, modify the row height and column width, and save the changes.

// Load the existing spreadsheet from a file named "sample.xlsx"
WorkBook workBook = WorkBook.Load("sample.xlsx");

// Get the default worksheet from the loaded workbook
WorkSheet workSheet = workBook.DefaultWorkSheet;

// Retrieve the first row (index 0) and set its height to 10 units
RangeRow row = workSheet.GetRow(0);
row.Height = 10;

// Retrieve the first column (index 0) and set its width to 10 units
RangeColumn col = workSheet.GetColumn(0);
col.Width = 10;

// Save the workbook with the updated row height and column width to a new file
workBook.SaveAs("manualHeightAndWidth.xlsx");
Imports IronXL



' This program demonstrates how to load an existing Excel file, modify the row height and column width, and save the changes.



' Load the existing spreadsheet from a file named "sample.xlsx"

Private workBook As WorkBook = WorkBook.Load("sample.xlsx")



' Get the default worksheet from the loaded workbook

Private workSheet As WorkSheet = workBook.DefaultWorkSheet



' Retrieve the first row (index 0) and set its height to 10 units

Private row As RangeRow = workSheet.GetRow(0)

row.Height = 10



' Retrieve the first column (index 0) and set its width to 10 units

Dim col As RangeColumn = workSheet.GetColumn(0)

col.Width = 10



' Save the workbook with the updated row height and column width to a new file

workBook.SaveAs("manualHeightAndWidth.xlsx")
$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.

Frequently Asked Questions

What is IronXL?

IronXL is a C# library that provides functionality to manipulate Excel files, including automatically resizing rows and columns without using Interop.

How do I auto resize rows in Excel using IronXL?

You can use the AutoSizeRow method to automatically adjust the height of rows based on their content using IronXL.

Can IronXL resize columns automatically?

Yes, IronXL allows you to use the AutoSizeColumn method to automatically adjust the width of columns based on their content.

Does IronXL support resizing of merged cells?

IronXL supports resizing of merged cells by using a Boolean parameter in the AutoSizeRow and AutoSizeColumn methods to consider merged cells.

What is the difference between Excel and IronXL auto resize functions?

Excel's auto resize functions apply noticeable padding to cells, while IronXL provides more direct control over cell dimensions without additional padding.

How can I manually resize rows and columns using IronXL?

You can manually set the height and width of rows and columns by adjusting the Height and Width properties of RangeRow and RangeColumn in IronXL.

What units are used for setting height and width in Excel?

In Excel, height is measured in 1/20 of a point, and width is measured by the number of '0's that fit using the font in the 'Normal' style.

Can IronXL handle Excel files without using Interop?

Yes, IronXL can manipulate Excel files directly in C# without the need for Microsoft Office Interop.

What are the benefits of using IronXL for resizing in Excel?

IronXL automates the process of resizing rows and columns, saving time and effort compared to manual adjustments in Excel.

Is there a video tutorial available for using IronXL?

Yes, there is a video tutorial available on resizing rows and columns using IronXL, which can be found on YouTube.

Chaknith related to Height and Width Units in Excel
Software Engineer
Chaknith is the Sherlock Holmes of developers. It first occurred to him he might have a future in software engineering, when he was doing code challenges for fun. His focus is on IronXL and IronBarcode, but he takes pride in helping customers with every product. Chaknith leverages his knowledge from talking directly with customers, to help further improve the products themselves. His anecdotal feedback goes beyond Jira tickets and supports product development, documentation and marketing, to improve customer’s overall experience.When he isn’t in the office, he can be found learning about machine learning, coding and hiking.