【问题标题】:Open XML Format not working打开 XML 格式不起作用
【发布时间】:2018-06-09 17:58:16
【问题描述】:

我正在尝试格式化 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;
    }

【问题讨论】:

  • 您是否运行过OpenXml productivity tool? 这应该可以帮助您确定是什么破坏了您的 excel 文件。
  • 不,我没有。我不知道。谢谢

标签: c# excel openxml


【解决方案1】:

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

https://github.com/ClosedXML/ClosedXML

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

【讨论】:

  • 我有一个使用 Interop 的实现,但由于技术问题,我改为使用 Open XML。我能够重用我的旧代码。只是有必要进行一些调整,但它确实节省了我的一周。所以我会接受这是一个有效的答案
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-12-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多