就像爱德华已经说过的那样,您需要创建一个样式表对象。
var stylesheet = new Stylesheet() { MCAttributes = new MarkupCompatibilityAttributes() {Ignorable = "x14ac"}};
stylesheet.AddNamespaceDeclaration("mc", "http: //schemas.openxmlformats.org/markup-compatibility/2006");
stylesheet.AddNamespaceDeclaration("x14ac", "http: //schemas.microsoft.com/office/spreadsheetml/2009/9/ac");
样式表对象必须包含您要使用的所有字体、填充、单元格格式等。
// create collections for fonts, fills, cellFormats, ...
var fonts = new Fonts() { Count = 1U, KnownFonts = true };
var fills = new Fills() {Count = 5U};
var cellFormats = new CellFormats() { Count = 4U };
// create a font: bold, red, calibr
Font font = new Font();
font.Append(new FontSize() {Val = 11D});
font.Append(new Color() { Rgb = "ff0000"});
font.Append(new FontName() {Val = "Calibri"});
font.Append(new FontFamilyNumbering() {Val = 2});
font.Append(new FontScheme() {Val = FontSchemeValues.Minor});
font.Append(new Bold());
// add the created font to the fonts collection
// since this is the first added font it will gain the id 1U
fonts.Append(font);
// create a background: green
Fill fill = new Fill();
var patternFill = new PatternFill() {PatternType = PatternValues.Solid};
patternFill.Append(new ForegroundColor() {Rgb = "00ff00"});
patternFill.Append(new BackgroundColor() {Indexed = 64U});
fill.Append(patternFill);
fills.Append(fill);
// create a cell format (combining font and background)
// the first added font/fill/... has the id 0. The second 1,...
cellFormats.AppendChild(new CellFormat(){ FontId = 0U, FillId = 0U });
// add the new collections to the stylesheet
stylesheet.Append(fonts);
stylesheet.Append(fills);
stylesheet.Append(cellFormats);
将样式表分配给您的工作簿部分对象
var stylePart = workbookpart.AddNewPart<WorkbookStylesPart>();
stylePart.Stylesheet = stylesheet;
stylePart.Stylesheet.Save();
之后,您可以将 CellStyleId 分配给单元格。
var cell = new Cell() {
CellValue = new CellValue("your cooler string"),
DataType = new EnumValue<CellValues>(CellValues.String),
StyleIndex = 0U // index in the cellFormats array
};
为 CellFormats 等对象分配字体、填充、边框等
Each Font
, Fill
, Border
, ... 可以通过相应集合中的索引分配给其他对象。例如,第一个添加到字体对象的字体将具有索引1U
.
这些索引表示为无符号整数(没有负值大于正值)。 “U”后缀表示 uint 或 ulong。
links
OpenXml 文档, 无符号整数