如何正确创build单元格格式?

我有一个两个单元格格式:

var stylesPart = spreadsheetDocument.WorkbookPart.AddNewPart<WorkbookStylesPart>(); stylesPart.Stylesheet = new Stylesheet(); // blank font list stylesPart.Stylesheet.Fonts = new Fonts(); stylesPart.Stylesheet.Fonts.Count = 2; stylesPart.Stylesheet.Fonts.AppendChild(new Font(new Bold(), new FontSize() {Val = 14})); stylesPart.Stylesheet.Fonts.AppendChild(new Font(new FontSize() {Val = 12})); // cell format list stylesPart.Stylesheet.CellFormats = new CellFormats(); stylesPart.Stylesheet.CellFormats.AppendChild(new CellFormat { FormatId = 0, FontId = 0, ApplyFont = true }); stylesPart.Stylesheet.CellFormats.AppendChild(new CellFormat { FormatId = 1, FontId = 1, ApplyFont = true }); stylesPart.Stylesheet.CellFormats.Count = 2; stylesPart.Stylesheet.Save(); 

当我使用它们中的任何一个来创build我的Excel文档时,我会在尝试打开文档时收到一条消息,即文档在/xl/styles.xml (Styles)有错误;

什么可能是错的?

在Excel表格中,您需要按照特定顺序创build样式表。 你没有做的就是遵循这个命令[正如我在代码示例中提供的]。 学习实际样式表结构的最简单方法使用打开XMl Productivity 。 您可以分析任何Excel文件的内容,也validation格式化[一个很好的教程]

作为支持,我为工作簿提供了基本样式表的代码。 这是你应该有的正确的顺序。 [这里我提供了2种样式的代码,样式索引0默认和1个alignment的污点文本]

  WorkbookStylesPart stylesheet = spreadsheet.WorkbookPart.AddNewPart<WorkbookStylesPart>(); Stylesheet workbookstylesheet = new Stylesheet(); // <Fonts> Font font0 = new Font(); // Default font Font font1 = new Font(); // Bold font Bold bold = new Bold(); font1.Append(bold); Fonts fonts = new Fonts(); // <APENDING Fonts> fonts.Append(font0); fonts.Append(font1); // <Fills> Fill fill0 = new Fill(); // Default fill Fills fills = new Fills(); // <APENDING Fills> fills.Append(fill0); // <Borders> Border border0 = new Border(); // Defualt border Borders borders = new Borders(); // <APENDING Borders> borders.Append(border0); // <CellFormats> CellFormat cellformat0 = new CellFormat() { FormatId = 0, FillId = 0, BorderId = 0 }; CellFormat cellformat1 = new CellFormat(new Alignment() { Horizontal HorizontalAlignmentValues.Center, Vertical = VerticalAlignmentValues.Center }) { FontId = 1 }; // <APENDING 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); stylesheet.Stylesheet = workbookstylesheet; stylesheet.Stylesheet.Save(); 

注 – 在您的具体情况下,您省略了所需的填充和边界。