简体   繁体   中英

Apply color to entire Excel row using OpenXml

I'm trying to color an entire row using OpenXml but can't seem to get it. I'm able to color individual cells just fine. When I'm adding a row, if it's the first row, I try to apply the 4th cell format (yellow), otherwise normal. Any help would be appreciated here.

Here's the code I'm working with:

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

Here's the creation of the style sheets:

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
        }

Assignment of stylesheet to workbookpart

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

It turns out that after looking at the "Compare Files..." feature in the OpenXml Productivity Tool , I was not setting the style in all the appropriate places.

The style index on a row only applies that style to cells in that row that haven't been defined yet. Custom format also needs to be set to true. Cells in the row that have been defined already need to have the style also explicitly assigned to them. Here's my working code:

Style Index 0 = Normal Default Formatting

Style Index 4 = Blue Header Formatting I've defined elsewhere

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM