使用 OpenXml 将颜色应用于整个 Excel 行

Apply color to entire Excel row using OpenXml

我正在尝试使用 OpenXml 为整行着色,但似乎无法实现。我能够很好地为单个细胞着色。当我添加一行时,如果它是第一行,我会尝试应用第 4 种单元格格式(黄色),否则正常。如有任何帮助,我们将不胜感激。

这是我正在使用的代码:

    public static Row WriteRow(uint rowIndex, WorksheetPart worksheetPart, string[] values)
    {
        var sheetData = worksheetPart.Worksheet.GetFirstChild<SheetData>();
        var lastRow = sheetData.Elements<Row>().LastOrDefault();
        if (lastRow == null || lastRow.RowIndex < rowIndex)
            sheetData.AppendChild(new Row() { RowIndex = rowIndex, CustomFormat = true, StyleIndex = rowIndex == 1u ? 4u : 0u});

        Row sheetRow = sheetData.Elements<Row>().ElementAt((int)rowIndex - 1);

        int colIndex = 1;
        foreach (string value in values)
        {
            sheetRow.AppendChild(
                new Cell()
                {
                    CellReference = $"{GetExcelColumnName(colIndex++)}{rowIndex}",
                    CellValue = new CellValue(value),
                    DataType = CellValues.String
                });
        }

        return sheetRow;
    }

样式表的创建如下:

public static Stylesheet GenerateStyleSheet()
        {
            return new Stylesheet(
                new Fonts(
                    new Font(                                                               // Index 0 - The default font.
                        new FontSize() { Val = 11 },
                        new Color() { Rgb = new HexBinaryValue() { Value = "00000000" } },
                        new FontName() { Val = "Calibri" }),
                    new Font(                                                               // Index 1 - The bold font.
                        new Bold(),
                        new FontSize() { Val = 11 },
                        new Color() { Rgb = new HexBinaryValue() { Value = "00000000" } },
                        new FontName() { Val = "Calibri" }),
                    new Font(                                                               // Index 2 - The Italic font.
                        new Italic(),
                        new FontSize() { Val = 11 },
                        new Color() { Rgb = new HexBinaryValue() { Value = "00000000" } },
                        new FontName() { Val = "Calibri" }),
                    new Font(                                                               // Index 2 - The Times Roman font. with 16 size
                        new FontSize() { Val = 16 },
                        new Color() { Rgb = new HexBinaryValue() { Value = "00000000" } },
                        new FontName() { Val = "Times New Roman" })
                ),
                new Fills(
                    new Fill(                                                           // Index 0 - The default fill.
                        new PatternFill() { PatternType = PatternValues.None }),
                    new Fill(                                                           // Index 1 - The default fill of gray 125 (required)
                        new PatternFill() { PatternType = PatternValues.Gray125 }),
                    new Fill(                                                           // Index 2 - The yellow fill.
                        new PatternFill(
                            new ForegroundColor() { Rgb = new HexBinaryValue() { Value = "FFFFFF00" } }
                        )
                        { PatternType = PatternValues.Solid })
                ),
                new Borders(
                    new Border(                                                         // Index 0 - The default border.
                        new LeftBorder(),
                        new RightBorder(),
                        new TopBorder(),
                        new BottomBorder(),
                        new DiagonalBorder()),
                    new Border(                                                         // Index 1 - Applies a Left, Right, Top, Bottom border to a cell
                        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())
                ),
                new CellFormats(
                    new CellFormat() { FontId = 0, FillId = 0, BorderId = 0 },                          // Index 0 - The default cell style.  If a cell does not have a style index applied it will use this style combination instead
                    new CellFormat() { FontId = 1, FillId = 0, BorderId = 0, ApplyFont = true },       // Index 1 - Bold 
                    new CellFormat() { FontId = 2, FillId = 0, BorderId = 0, ApplyFont = true },       // Index 2 - Italic
                    new CellFormat() { FontId = 3, FillId = 0, BorderId = 0, ApplyFont = true },       // Index 3 - Times Roman
                    new CellFormat() { FontId = 0, FillId = 2, BorderId = 0, ApplyFill = true },       // Index 4 - Yellow Fill
                    new CellFormat(                                                                   // Index 5 - Alignment
                        new Alignment() { Horizontal = HorizontalAlignmentValues.Center, Vertical = VerticalAlignmentValues.Center }
                    )
                    { FontId = 0, FillId = 0, BorderId = 0, ApplyAlignment = true },
                    new CellFormat() { FontId = 0, FillId = 0, BorderId = 1, ApplyBorder = true }      // Index 6 - Border
                )
            ); // return
        }

将样式表分配给工作簿部分

SpreadsheetDocument sheet = XlsxWriterHelper.CreateWorkbook(filePath)
sheet.WorkbookPart.WorkbookStylesPart.Stylesheet = XlsxWriterHelper.GenerateStyleSheet();
sheet.WorkbookPart.WorkbookStylesPart.Stylesheet.Save();

事实证明,在查看 OpenXml Productivity Tool 中的 "Compare Files..." 功能后,我没有在所有适当的地方设置样式。

某行的样式索引仅将该样式应用于该行中尚未定义的单元格。自定义格式也需要设置为 true。已定义的行中的单元格也需要显式分配给它们的样式。这是我的工作代码:

样式索引 0 = 正常默认格式

样式索引 4 = 蓝色 Header 我在别处定义的格式

public static Row WriteRow(uint rowIndex, WorksheetPart worksheetPart, string[] values)
{
    var sheetData = worksheetPart.Worksheet.GetFirstChild<SheetData>();
    var lastRow = sheetData.Elements<Row>().LastOrDefault();
    if (lastRow == null || lastRow.RowIndex < rowIndex)
        sheetData.AppendChild(new Row() { RowIndex = rowIndex, CustomFormat = true, StyleIndex = rowIndex == 1u ? 4u : 0u });

    Row sheetRow = sheetData.Elements<Row>().ElementAt((int)rowIndex - 1);

    int colIndex = 1;
    foreach (string value in values)
    {
        sheetRow.AppendChild(
            new Cell()
            {
                CellReference = $"{GetExcelColumnName(colIndex++)}{rowIndex}",
                CellValue = new CellValue(value),
                DataType = CellValues.String,
                StyleIndex = rowIndex == 1u ? 4u : 0u
            });
    }

    return sheetRow;
}