29

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

krabcore
  • 885
  • 2
  • 8
  • 22

5 Answers5

33

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

Twenty
  • 5,234
  • 4
  • 32
  • 67
Francois Botha
  • 4,520
  • 1
  • 34
  • 46
22
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.

kamlesh jha
  • 361
  • 2
  • 8
10

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

Majid Basirati
  • 2,665
  • 3
  • 24
  • 46
Aman Sengar
  • 109
  • 1
  • 2
3

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.

Caverman
  • 3,371
  • 9
  • 59
  • 115
0

try below code.

foreach (var item in worksheet.ColumnsUsed())
{
    item.AdjustToContents();
}
xmsoy
  • 1
  • 2