AutoFit Column Widths and Row Heights in Excel

When we operate the excel files with large amounts of data, we may find that some of the cells need to be widened to allow the data to fit. Spire.XLS offers a method worksheet.AutoFitColumn(); and worksheet.AutoFitRow(); to enable developers to adjust the widths of the columns and the height of the rows to fit the content and make the whole Excel worksheet tidy and clean. This article will demonstrate how to auto fit the columns and rows in Excel worksheet in C#.

Note: Before Start, please download the latest version of Spire.XLS and add Spire.Xls.dll in the bin folder as the reference of Visual Studio.

Firstly please check the Excel worksheet need to AutoFit the columns and rows:

AutoFit Column Widths and Row Heights in Excel

Step 1: Create a new Excel workbook and load from file.

Workbook workbook = new Workbook();
workbook.LoadFromFile("Sample.xlsx");

Step 2: Get the first worksheet from the workbook.

Worksheet worksheet = workbook.Worksheets[0];

Step 3: AutoFit the whole worksheets Column widths and Row heights.

worksheet.AllocatedRange.AutoFitColumns();
worksheet.AllocatedRange.AutoFitRows();

Step 4: Save the document to file.

workbook.SaveToFile("Result.xlsx", FileFormat.Version2010);

Effective screenshot after AutoFit and rows and columns in Excel:

AutoFit Column Widths and Row Heights in Excel

Full codes:

{
    Workbook workbook = new Workbook();
    workbook.LoadFromFile("Sample.xlsx");

    Worksheet worksheet = workbook.Worksheets[0];

    worksheet.AllocatedRange.AutoFitColumns();
    worksheet.AllocatedRange.AutoFitRows();

    workbook.SaveToFile("Result.xlsx", FileFormat.Version2010);
}