Search code examples
c#excelautosize

How to Auto size Excel ClosedXml cells in c#


I am trying to resize cells so that it fits the maximum length of the text using ClosedXMl.Excel but the cell is giving me this error message:

Severity Code Description Project File Line Suppression State Error CS0119 'IXLRangeBase.Cells()' is a method, which is not valid in the given context

C#:

var workbook = new XLWorkbook();     //creates the workbook
var wsDetailedData = workbook.AddWorksheet("data"); //creates the worksheet with sheetname 'data'

wsDetailedData.Cell(1, 1).InsertTable(dataList); //inserts the data to cell A1 including default column name
wsDetailedData.Cells.SizeToContent = true;
workbook.SaveAs(@"C:\data.xlsx"); //saves the workbook

Solution

  • You can try to adjust the column & Rows instead of adjusting the cell:

    wsDetailedData.Columns().AdjustToContents();  // Adjust column width
    wsDetailedData.Rows().AdjustToContents();     // Adjust row heights