Применить цвет ко всей строке Excel, используя OpenXml - PullRequest
0 голосов
/ 13 февраля 2020

Я пытаюсь раскрасить всю строку, используя Open Xml, но не могу ее получить. Я могу покрасить отдельные клетки просто отлично. Когда я добавляю строку, если это первая строка, я пытаюсь применить 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
        }

Назначение таблица стилей для workbookpart

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

1 Ответ

0 голосов
/ 13 февраля 2020

Оказывается, что после просмотра функции "Сравнить файлы ..." в Open Xml Productivity Tool я не устанавливал стиль во всех соответствующих местах.

Индекс стиля в строке применяет этот стиль только к ячейкам в этой строке, которые еще не определены. Пользовательский формат также должен быть установлен в true. Ячейки в строке, которые были определены, уже должны иметь стиль, также явно назначенный им. Вот мой рабочий код:

Индекс стиля 0 = Нормальное форматирование по умолчанию

Индекс стиля 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,
                StyleIndex = rowIndex == 1u ? 4u : 0u
            });
    }

    return sheetRow;
}
...