【问题标题】:Apply color to entire Excel row using OpenXml使用 OpenXml 将颜色应用于整个 Excel 行
【发布时间】:2020-02-25 02:22:48
【问题描述】:

我正在尝试使用 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();

【问题讨论】:

  • 拿走你的无色纸并保存。在 Excel 中打开它,然后再次保存。然后执行您想要的操作(使用 Excel UI),并将结果保存在另一个名称下。然后从 Microsoft 站点下载 OpenXML Productivity Tool 并比较您保存的最后两个文件。它应该向您展示您想要做什么。值得一提的是,该工具可以解决许多 OpenXML 编程问题

标签: c# excel openxml


【解决方案1】:

事实证明,在查看 OpenXml 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;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-11-25
    • 2017-05-22
    • 1970-01-01
    • 2012-02-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多