Autofit column in ClosedXML.Excel
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.
You need to give the range of the columns.
Example: wsDep.Columns("A","H").AdjustToContents();
Your cells don't have any contents.Therefore AdjustToContents()
won't have any effect.
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.