Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make Excel wrap text in formula cell with ClosedXml

The problem is that the cell content is not wrapped, when that cell contains a formula referring to a cell with some long string.

On CodePlex I found a thread on this issue and a simple code to see the problem:

var generated = new XLWorkbook();
var workSheet = generated.AddWorksheet("Test");
workSheet.Cell("B1").Style.Alignment.WrapText = true;
workSheet.Cell("B1").Value = "hello hello hello hello hello";
workSheet.Cell("A3").FormulaA1 = "B1";
workSheet.Cell("A3").Style.Alignment.WrapText = true;
generated.SaveAs("Generated.xlsx");

I also tried to set row height manually instead of wrapping the cell:

workSheet.Row(3).Height = workSheet.Row(1).Height;

However to no success either.

Is there anything I can do about this?


Following the comment by Peter Albert, I tried to make the set row's AutoFit. The only thing I managed to find to do this in ClosedXML is workSheet.Row(3).AdjustToContent();. But this did not work either (neither adjusting the content of certain column).

like image 382
horgh Avatar asked Mar 04 '13 09:03

horgh


1 Answers

Instead of Applying the Adjust to Contents, you can apply the Wraptext like this

var generated = new XLWorkbook();
var workSheet = generated.AddWorksheet("Test");
worksheet.Cell(3, 2).Value = "Hello Hello Hello Hello Hello Hello Name";    
worksheet.Cell(3, 2).Style.Alignment.WrapText = true;

And if you want to apply both use it after AdjustToContents.

var generated = new XLWorkbook();
var workSheet = generated.AddWorksheet("Test");
worksheet.Columns(2, 20).AdjustToContents();    
worksheet.Cell(3, 2).Value = "Hello Hello Hello Hello Hello Hello Name";
worksheet.Cell(3, 2).Style.Alignment.WrapText = true;
like image 167
Smit Patel Avatar answered Oct 14 '22 13:10

Smit Patel