Dynamically AutoFit Columns in Excel Addin C#

Dynamically AutoFit Columns in Excel Addin C#

AutoFit:

AutoFit is a property associated to Range object exposed by Microsoft Excel which allows automatically expand or shrink columns width based on contents. In this article we will see an example, how to manipulate or change column width using VSTO C# Excel.

Prerequisites:

  • Visual Studio 2015 or above having Microsoft Office for Developer Tool installed
  • Create Excel Addin in C# code style (Visual Studio Tools for Office)
  • Create a ribbon designer and put button

Following is the input source which looks messy at initial stage. Let’s put some code and see how the formatting gets changed:

Code example:

private void btnAutoFitcolumnWidth_Click(object sender, RibbonControlEventArgs e)
{
	//retain active row selection
	excel.Range oRange = Globals.ThisAddIn.Application.Selection;
	//Autofit column with
	oRange.Columns.AutoFit();
}

Run above code by selecting all three columns as shown in input Image above and check result it should look like below:

Wow!!! that’s what we were expecting as final output. Please leave your valuable comments!!!

Next : Change column width in Excel C#

Leave a Reply

Your email address will not be published. Required fields are marked *