【问题标题】:How to add colour to particular excel columns based on conditions using openxml?如何使用openxml根据条件为特定的excel列添加颜色?
【发布时间】:2019-02-14 05:41:42
【问题描述】:

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

我正在使用 open XML 来生成 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;
    }

有没有办法解决这个问题?

【问题讨论】:

    标签: c# openxml


    【解决方案1】:

    1) 将样式表添加到您的 WorkBookPart

    WorkbookPart workbookPart = document.AddWorkbookPart();
    workbookPart.Workbook = new Workbook();
    
    WorkbookStylesPart stylePart = workbookPart.AddNewPart<WorkbookStylesPart>();
    stylePart.Stylesheet = GenerateStylesheet();
    stylePart.Stylesheet.Save();
    

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

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

    【讨论】:

    • 非常感谢您的努力。让我试试这个
    • 在打开 excel 之前显示错误 已修复记录:来自 /xl/worksheets/sheet1.xml 部分的单元格信息 并且所有列的颜色相同,即红色
    • 告诉我你是如何实现我对你的代码的回答的?在您的帖子中添加您的代码
    • 在此行下方添加此 stylePart 代码 => workbookPart.Workbook = new Workbook(); 请参阅我的步骤 1
    • 非常感谢您回复我,我找到了解决方案并且它的工作原理。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-25
    • 2015-10-06
    • 2019-04-09
    • 1970-01-01
    • 2022-10-17
    相关资源
    最近更新 更多