How to Set Width of Cell in Excel using C#

This short tutorial contains information on how to set width of cell in Excel using C#. By using C# Excel column width can be adjusted in a variety of ways with the help of the step-by-step process described in this tutorial. You can set column width in different units as per the requirement and save the output file in any of the desired formats like XLSX, XLS, ODS, etc.

Steps to Set Width of Cell in Excel using C#

  1. Establish the environment by adding Aspose.Cells from Nuget package manager
  2. Instantiate a Workbook class object to set the column width
  3. Get access to the target worksheet from the default collection in the workbook
  4. Use the SetColumnWidth() function to set the column width
  5. Save the output Excel file having the specified column width

These steps has explained how with the help of C# Excel cell width can be set. After establishing the environment you can create or load an Excel file and then set the desired worksheet whose cell width is to be modified. By using the Worksheet.Cells.SetColumnWidth(), you can set the column width by providing the column number and column width.

Code to Set Width of Cell in Excel using C#

By using the C# Excel column autofit feature can also be implemented for the selected rows in a worksheet by using the Worksheet.AutoFitColumn() function where the first argument is the column index and the last two arguments indicate the starting row and ending row. Similarly, if you want to set the standard column width for the entire sheet, set the Worksheet.Cells.StandardWidth property to the desired width. Cell width can be set in inches and pixels also using Worksheet.Cells.SetColumnWidthInch() and Worksheet.Cells.SetColumnWidthPixel() functions.

In this article, we have learned how to set the column width. If you want to work with the row height, refer to the article on how to adjust row height in Excel using C#.

 English