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); } } }
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.