如何使用 openxml 根据条件向特定 excel 列添加颜色?

How to add colour to particular excel columns based on conditions using openxml?

我正在生成 excel sheet,我想根据条件为 excel 列着色。现在我的所有 excel 列都变成了红色。我只想为特定的列名称着色。

我正在使用 open XML 生成 excel,有什么方法可以找到要应用颜色的单元格

 using (SpreadsheetDocument document = SpreadsheetDocument.Create(path, SpreadsheetDocumentType.Workbook))
            {
                WorkbookPart workbookPart = document.AddWorkbookPart();
                workbookPart.Workbook = new Workbook();

                WorksheetPart worksheetPart = workbookPart.AddNewPart<WorksheetPart>();
                worksheetPart.Worksheet = new Worksheet();

                Sheets sheets = workbookPart.Workbook.AppendChild(new Sheets());

                Sheet sheet = new Sheet() { Id = workbookPart.GetIdOfPart(worksheetPart), SheetId = 1, Name = "Template" };

                sheets.Append(sheet);

                var 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");

                var fills = new Fills() { Count = 5U };
                var fonts = new Fonts() { Count = 1U, KnownFonts = true };
               // var cellFormats = new CellFormats();
                Font font = new Font();
                font.Append(new Color() { Rgb = "ff0000" });
                fonts.Append(font);

               // cellFormats.AppendChild(new CellFormat() { FontId = 0U });
                stylesheet.Append(fonts);
                stylesheet.Append(fills);
                //stylesheet.Append(cellFormats);
                //stylesheet.Append(fill);                 
                var stylePart = workbookPart.AddNewPart<WorkbookStylesPart>();
                stylePart.Stylesheet = stylesheet;
                stylePart.Stylesheet.Save();

                workbookPart.Workbook.Save();

                SheetData sheetData = worksheetPart.Worksheet.AppendChild(new SheetData());

                // Constructing header
                Row row = new Row();

                foreach (DataExchangeDefinition a in importColList)
                {
                    defnExist = true;
                    if (a.MustFieldYN == true)
                    {
                        row.Append(
                        ConstructCell(a.FieldCaption, CellValues.String));
                    }
                    else
                    {
                        row.Append(
                        ConstructCell(a.FieldCaption, CellValues.String));
                    }
                }

                if (defnExist == false)
                {
                    row.Append(
                    ConstructCell("Excel Template Definition Missing", CellValues.String));
                }
                // Insert the header row to the Sheet Data
                sheetData.AppendChild(row);

                // Inserting each employee

                worksheetPart.Worksheet.Save();
            }

这里是构造单元格的方法

 private Cell ConstructCell(string value, CellValues dataType)
    {
        Cell c = new Cell()
        {
            CellValue = new CellValue(value),
            DataType = new EnumValue<CellValues>(dataType)
            //StyleIndex=0U                
        };
        return c;
    }

有什么办法可以解决吗?

1) 将样式 sheet 添加到您的 WorkBookPart

WorkbookPart workbookPart = document.AddWorkbookPart();
workbookPart.Workbook = new Workbook();

WorkbookStylesPart stylePart = workbookPart.AddNewPart<WorkbookStylesPart>();
stylePart.Stylesheet = GenerateStylesheet();
stylePart.Stylesheet.Save();

注意:WorkbookPart 下方添加 WorkbookStylesPart 代码,否则无法正常工作。

2) 添加以下函数 return stylesheet,

private Stylesheet GenerateStylesheet()
    {
        Stylesheet styleSheet = null;

        Fonts fonts = new Fonts(
            new Font( // Index 0 - default
                new FontSize() { Val = 10 }

            ),
            new Font( // Index 1 - header
                new FontSize() { Val = 10 },
                new Bold(),
                new Color() { Rgb = "FFFFFF" }

            ));

        Fills fills = new Fills(
                new Fill(new PatternFill() { PatternType = PatternValues.None }), // Index 0 - default
                new Fill(new PatternFill() { PatternType = PatternValues.Gray125 }), // Index 1 - default
                new Fill(new PatternFill(new ForegroundColor { Rgb = new HexBinaryValue() { Value = "66666666" } })
                { PatternType = PatternValues.Solid }) // Index 2 - header
            );

        Borders borders = new Borders(
                new Border(), // index 0 default
                new Border( // index 1 black border
                    new LeftBorder(new Color() { Auto = true }) { Style = BorderStyleValues.Thin },
                    new RightBorder(new Color() { Auto = true }) { Style = BorderStyleValues.Thin },
                    new TopBorder(new Color() { Auto = true }) { Style = BorderStyleValues.Thin },
                    new BottomBorder(new Color() { Auto = true }) { Style = BorderStyleValues.Thin },
                    new DiagonalBorder())
            );

        CellFormats cellFormats = new CellFormats(
                new CellFormat(), // default
                new CellFormat { FontId = 0, FillId = 0, BorderId = 1, ApplyBorder = true }, // body
                new CellFormat { FontId = 1, FillId = 2, BorderId = 1, ApplyFill = true } // header
            );

        styleSheet = new Stylesheet(fonts, fills, borders, cellFormats);

        return styleSheet;
    }

3) 还有你的 ConstructCell 方法,

private Cell ConstructCell(string value, CellValues dataType, uint styleIndex = 0)
{
    return new Cell()
    {
        CellValue = new CellValue(value),
        DataType = new EnumValue<CellValues>(dataType),
        StyleIndex = styleIndex
    };
}

4) 并像

这样调用上面的方法

如果您不想应用样式,请使用以下内容

ConstructCell(a.FieldCaption, CellValues.String));

如果您想在 body 单元格上应用样式,请使用下面的

ConstructCell(a.FieldCaption, CellValues.String, 1);

如果您想在 header 单元格上应用样式,请使用下面的

ConstructCell(a.FieldCaption, CellValues.String, 2);