Open XML格式无效

时间:2018-06-08 21:13:09

标签: c# excel openxml

我正在尝试格式化Excel表格。标题应该有粗体字和橙色背景。当我打开工作表时,Excel会给出一个错误,指出文档无效,并且打开时所有单元格都是粗体,而且标题中没有背景。

这就是设定风格的方式。

.....

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;
    }

1 个答案:

答案 0 :(得分:1)

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

https://github.com/ClosedXML/ClosedXML

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