How do you add text wrapping to a cell using OpenXml when creating excel files?
You need to define styles for this. Styles are defined inside a stylesheet. Each style has an ID and when you create Cells you can refer defined style ID.
Defining stylesheet for the spreadsheet:
private WorkbookStylesPart AddStyleSheet(SpreadsheetDocument spreadsheet)
{
WorkbookStylesPart stylesheet = spreadsheet.WorkbookPart.AddNewPart<WorkbookStylesPart>();
Stylesheet workbookstylesheet = new Stylesheet();
// <Fonts>
Font font0 = new Font(); // Default font
Fonts fonts = new Fonts(); // <APPENDING Fonts>
fonts.Append(font0);
// <Fills>
Fill fill0 = new Fill(); // Default fill
Fills fills = new Fills(); // <APPENDING Fills>
fills.Append(fill0);
// <Borders>
Border border0 = new Border(); // Defualt border
Borders borders = new Borders(); // <APPENDING Borders>
borders.Append(border0);
// <CellFormats>
CellFormat cellformat0 = new CellFormat() // Default style : Mandatory
{
FontId = 0,
FillId = 0,
BorderId = 0
};
CellFormat cellformat1 = new CellFormat(new Alignment() { WrapText = true }); // Style with textwrap set
// <APPENDING CellFormats>
CellFormats cellformats = new CellFormats();
cellformats.Append(cellformat0);
cellformats.Append(cellformat1);
// Append FONTS, FILLS , BORDERS & CellFormats to stylesheet <Preserve the ORDER>
workbookstylesheet.Append(fonts);
workbookstylesheet.Append(fills);
workbookstylesheet.Append(borders);
workbookstylesheet.Append(cellformats);
// Finalize
stylesheet.Stylesheet = workbookstylesheet;
stylesheet.Stylesheet.Save();
return stylesheet;
}
Now when you add cells, use the defined style ID as follows:
// Assign our defined style with text wrap.
Cell c1 = new Cell(){ StyleIndex = Convert.ToUInt32(1) };
EDIT: You need to add stylesheet after adding workbookpart.