我有两种单元格格式:
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();
Run Code Online (Sandbox Code Playgroud)
当我使用它们中的任何一个来创建我的Excel文档时,当尝试打开该文档时出现错误消息/xl/styles.xml (Styles);
有什么问题吗?
在Excel工作表中,您需要遵循特定的顺序来创建样式表。您不要做的就是遵循此顺序[正如我在代码示例中提供的]。使用Open XMl Productivity工具来学习样式表的实际结构的最简单方法。您可以分析任何Excel文件的内容,也可以验证格式。[ 一个很好的教程 ]。
作为支持,我提供了工作簿基本样式表的代码。这是您应有的正确顺序。[这里提供了2种样式的代码,样式索引0是默认样式,样式索引1是带有对齐方式的污点文本。]
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
};
Alignment alignment = new Alignment()
{
Horizontal = HorizontalAlignmentValues.Center,
Vertical = VerticalAlignmentValues.Center
};
CellFormat cellformat1 = new CellFormat(alignment)
{
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();
Run Code Online (Sandbox Code Playgroud)
注意-在您的特定情况下,您省略了很多需要的“填充和边框”。