Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Autofit column in ClosedXML.Excel

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??

like image 284
krabcore Avatar asked Oct 04 '16 08:10

krabcore


4 Answers

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

like image 111
Francois Botha Avatar answered Sep 21 '22 09:09

Francois Botha


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

like image 42
Aman Sengar Avatar answered Sep 18 '22 09:09

Aman Sengar


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.

like image 27
kamlesh jha Avatar answered Sep 18 '22 09:09

kamlesh jha


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.

like image 23
Caverman Avatar answered Sep 18 '22 09:09

Caverman