23

I create cell with text. After that I set WrapText property and column width.

var cell = worksheet.Cell("A1");
cell.Style.Alignment.WrapText = true;
cell.SetValue("This is very long text");
worksheet.Column(1).Width = 10;
worksheet.Rows().AdjustToContents();

The text has been moved by words, but row height is not changed. How to adjust row height to cell content?

Raidri
  • 17,258
  • 9
  • 62
  • 65
Vlad
  • 1,377
  • 2
  • 17
  • 29

5 Answers5

18

There are many ways to achieve this.

Don't use wrap or shrink properties on cell values rather include this line just before saving your excel

ws.Columns().AdjustToContents();

Another way is to make use of Allignment property

 IXLRange titleRange = ws.Range("B2:AA2");
        titleRange.Cells().Style
            .Alignment.SetWrapText(true); // Its single statement

Hope it helps!!

16

It works when you remove the worksheet.Rows().AdjustToContents();.

Autofitting sometimes needs more of a trial and error approach ...

Raidri
  • 17,258
  • 9
  • 62
  • 65
3

I think this is a bug of ClosedXML. enter link description here

ws.Row(1).AdjustToContents();
ws.Row(1).ClearHeight();

In my case it works. Version: 0.95.4

ouflak
  • 2,458
  • 10
  • 44
  • 49
Lisar
  • 31
  • 1
1

The following code worked for me.

IXLRange contents = ws.Range("A1:A50");
contents.Style.Alignment.WrapText = true;
0

You can also AdjustToContents on Specific range of cells.

worksheet.Columns(2, 20).AdjustToContents();
Smit Patel
  • 2,992
  • 1
  • 26
  • 44
  • Question is about adjusting the height, not columns. – Himalaya Garg Dec 15 '21 at 04:10
  • 7 Years later????? - I didn't remember the question :D – Smit Patel Dec 16 '21 at 09:22
  • @SmitPatel In that case, it's best if you delete your answer, since it doesn't answer the question! It adds nothing new that the other (more upvoted) answers haven't already covered. – Zimano Jan 18 '23 at 15:20
  • @Zimano - I've put it because of a Range can also be applied with AdjustToContents - Someone might have that question as well apart from what asked, As a developer we should think on wider level and don't need to stick to the exact question everytime. – Smit Patel Jan 21 '23 at 16:58