Wednesday, 27 February 2019 08:32

Shrink Text to Fit in a Cell in Excel in C#

Written by  support iceblue
Rate this item
(0 votes)

Shrink to fit is a useful option in Excel, it enables us to automatically reduce the font size in a cell until the text fits within the cell. This article demonstrates how to accomplish the same functionality programmatically in C# using Spire.XLS.

Below is the screenshot of the input Excel file:

Shrink Text to Fit in a Cell in Excel in C#

Detail steps:

Step 1: Instantiate a Workbook object and load the Excel file.

Workbook workbook = new Workbook();
workbook.LoadFromFile(@"Input.xlsx");

Step 2: Get the first worksheet.

Worksheet sheet = workbook.Worksheets[0];

Step 3: Specify the cell range to shrink text.

CellRange cell = sheet.Range["A1:E3"];

Step 4: Enable ShrinkToFit.

CellStyle style = cell.Style;
style.ShrinkToFit = true;

Step 5: Save the file.

workbook.SaveToFile("ShrinkTextToFitCell.xlsx", ExcelVersion.Version2013);

Output:

Shrink Text to Fit in a Cell in Excel in C#

Full code:

//Load the Excel file
Workbook workbook = new Workbook();
workbook.LoadFromFile(@"Input.xlsx");

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

//The cell range to shrink text
CellRange cell = sheet.Range["A1:E3"];

//Enable ShrinkToFit
CellStyle style = cell.Style;
style.ShrinkToFit = true;

//Save the file
workbook.SaveToFile("ShrinkTextToFitCell.xlsx", ExcelVersion.Version2013);

Additional Info

  • tutorial_title: