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
Post a Comment