Autofit column in ClosedXML.Excel

25,060

Solution 1

Your cells don't have any contents.Therefore AdjustToContents() won't have any effect.

Solution 2

You need to give the range of the columns.
Example: wsDep.Columns("A","H").AdjustToContents();

Solution 3

wsDep.Columns().AdjustToContents();

You should write this code at the end of your code section because it's working only when you write it at the end of your code.

Solution 4

Adding to an old post in case someone comes across this one like I did. My fix was to use the worksheet.Columns().AdjustToContents(); but I had to add it after I wrote out all of the data. Initially I was setting it when I was setting up all of my column headers and colors during up creation of the worksheet and it wasn't working. I then came across this thread and it made me think that it was adjusting the contents at the point that I was calling the AdjustToContents which in my case have anything more than the column headers at that point. I moved it to the end after writing out all of my data and it worked as expected and actually makes sense as to what it was doing.

Share:
25,060
krabcore
Author by

krabcore

Updated on July 21, 2022

Comments

  • krabcore
    krabcore almost 2 years

    I understand that the question stupid and from FAQ, but i cant set auto width in excel columns (using ClosedXML.Excel library)

    my code:

    var wb = new XLWorkbook();
    var wsDep = wb.Worksheets.Add("MyWorksheet");
    wsDep.Columns("A").AdjustToContents();
    wsDep.Columns("B1").AdjustToContents();
    wsDep.Columns().AdjustToContents();
    

    but nothing changes. how can i set auto width columns with ClosedXML.Excel library??