打开 XML 格式无效

Open XML Format not working

我正在尝试格式化 Excel sheet。 header 应该有粗体和橙色背景。当我打开 sheet 时,Excel 给我一个错误,说文档无效,它打开时所有单元格都是粗体并且 header.

中没有背景

这是设置样式的方式。

.....

workbookStylePart = workbookpart.AddNewPart<WorkbookStylesPart>();
workbookStylePart.Stylesheet = CreateStylesheet();
workbookStylePart.Stylesheet.Save();
.....
cell.StyleIndex = 0U; // I suppose the style index is 0

这是样式定义:

    private static Stylesheet CreateStylesheet()
    {
        Stylesheet 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");

        Fonts fonts = new Fonts() { Count = 1U, KnownFonts = true };
        Font boldFont = new Font();
        Bold bold = new Bold();
        boldFont.Append(bold);

        fonts.Append(boldFont);

        Fills fills = new Fills() { Count = 1U };

        // FillId = 0, orange
        Fill orangeFill = new Fill();
        PatternFill orangePatternFill = new PatternFill() { PatternType = PatternValues.Solid };
        BackgroundColor orangeColor = new BackgroundColor() { Rgb = "FFA500" };
        orangePatternFill.Append(orangeColor);
        orangeFill.Append(orangePatternFill);

        fills.Append(orangeFill);

        CellFormats cellFormats = new CellFormats() { Count = 1U };
        CellFormat headerBoldOrangeBgFormat = new CellFormat() { FontId = 0U, FillId = 0U , ApplyFill = true};

        cellFormats.Append(headerBoldOrangeBgFormat);

        stylesheet.Append(fonts);
        stylesheet.Append(fills);
        stylesheet.Append(cellFormats);

        return stylesheet;
    }

ClosedXML 库是 OpenXML 的高级包装器。我建议您使用 ClosedXML。此外,还有一个 ClosedXML.Report 库可以根据 XLSX 模板生成 Excel 文件。

https://github.com/ClosedXML/ClosedXML

https://github.com/ClosedXML/ClosedXML.Report