Adding StyleSheet is a one-time job. After that, you just need to refer to a specific style identifier when creating new cells.
Hot to add a stylesheet to the table [Bold]
private WorkbookStylesPart AddStyleSheet(SpreadsheetDocument spreadsheet)
{
WorkbookStylesPart stylesheet = spreadsheet.WorkbookPart.AddNewPart<WorkbookStylesPart>();
Stylesheet workbookstylesheet = new Stylesheet();
Font font0 = new Font();
Font font1 = new Font();
Bold bold = new Bold();
font1.Append(bold);
Fonts fonts = new Fonts();
fonts.Append(font0);
fonts.Append(font1);
Fill fill0 = new Fill();
Fills fills = new Fills();
fills.Append(fill0);
Border border0 = new Border();
Borders borders = new Borders();
borders.Append(border0);
CellFormat cellformat0 = new CellFormat() { FontId = 0, FillId = 0, BorderId = 0 };
CellFormat cellformat1 = new CellFormat() { FontId = 1 };
CellFormats cellformats = new CellFormats();
cellformats.Append(cellformat0);
cellformats.Append(cellformat1);
workbookstylesheet.Append(fonts);
workbookstylesheet.Append(fills);
workbookstylesheet.Append(borders);
workbookstylesheet.Append(cellformats);
stylesheet.Stylesheet = workbookstylesheet;
stylesheet.Stylesheet.Save();
return stylesheet;
}
Now, when you create a cell, follow these steps to refer to the bold text
Cell c1 = new Cell(){StyleIndex = Convert.ToUInt32(1)};
Additional note: you need to add a stylesheet after adding a worksheet to the table.
More about the SAX approach: you can define styles the first time you create a template file that you want to open to insert data cells. And when adding data cells refers to certain styles using an identifier.
Simple Style Worksheet ( MSDN )
public static void CreateSpreadsheetWorkbook(string filepath)
{
SpreadsheetDocument spreadsheetDocument = SpreadsheetDocument.Create(filepath, SpreadsheetDocumentType.Workbook);
WorkbookPart workbookpart = spreadsheetDocument.AddWorkbookPart();
workbookpart.Workbook = new Workbook();
AddStyleSheet(spreadsheetDocument)
WorksheetPart worksheetPart = workbookpart.AddNewPart<WorksheetPart>();
worksheetPart.Worksheet = new Worksheet(new SheetData());
Sheets sheets = spreadsheetDocument.WorkbookPart.Workbook.AppendChild<Sheets>(new Sheets());
Sheet sheet = new Sheet() { Id = spreadsheetDocument.WorkbookPart.GetIdOfPart(worksheetPart), SheetId = 1, Name = "mySheet" };
sheets.Append(sheet);
workbookpart.Workbook.Save();
spreadsheetDocument.Close();
}
source
share