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

时间:2019-02-14 05:41:42

标签: c# openxml

我正在生成一个Excel工作表,我想根据条件为Excel列着色。现在,我所有的Excel列都变为红色。我只想为特定的列名称着色。

我使用openxml生成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 个答案:

答案 0 :(得分:2)

1)将样式表添加到WorkBookPart

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

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

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

2)以下添加了返回样式表的函数,

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

如果您想在人体细胞上应用样式,请在下方使用

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

如果要在标题单元格上应用样式,请在下面使用

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