使用DocumentFormat.OpenXml为条件着色Excel单元格

时间:2017-07-14 10:29:28

标签: spreadsheet

我想知道是否有人使用过DocumentFormat.OpenXml,因为我在使用DocumentFormat.Spreadsheet的条件下对单元格着色有问题。

现在我可以第一次创建颜色,但我需要打开相同的Excel工作表,并根据我需要为特定单元格着色的条件。例如。如果单元格D1为黄色,则D2可以为绿色或黄色。

e.g。

Name    IpAddress   Region  Details
Switch  10.1.1.1    EMEA    Based on Condition the cell would be coloured  
Switch  10.1.1.2    AMER    Based on Condition the cell would be coloured  
Switch  10.1.1.3    APAC    Based on Condition the cell would be coloured  
Switch  10.1.1.2    AMER    Based on Condition the cell would be coloured  
Switch  10.1.1.2    AMER    Based on Condition the cell would be coloured  

我每次都在写每一行,当我想打开现有的excel表时,我会传递值,即_valuecolour并根据其值,它将为特定单元格着色以及其他单元格的对齐。

我使用了以下代码。

public static bool InsertRowExcel(string filepath, string _sb, string _switchinput)
        {
            int i = 0;
            string[] _arr = _switchinput.Split(',');
            bool bl = false;
            int k = 0;
            try
            {
                using (SpreadsheetDocument myDoc = SpreadsheetDocument.Open(filepath, true))
                {
                    //Get workbookpart
                    WorkbookPart workbookPart = myDoc.WorkbookPart;
                    WorkbookStylesPart stylePart = workbookPart.WorkbookStylesPart;
                    Row row = new Row();
                    //then access to the worksheet part
                    IEnumerable<WorksheetPart> worksheetPart = workbookPart.WorksheetParts;
                    foreach (WorksheetPart WSP in worksheetPart)
                    {
                        //find sheet data
                        IEnumerable<SheetData> sheetData = WSP.Worksheet.Elements<SheetData>();
                        // Iterate through every sheet inside Excel sheet
                        foreach (SheetData SD in sheetData)
                        {
                            IEnumerable<Row> rows = SD.Elements<Row>(); // Get the row IEnumerator
                            i = (rows.Count()); // Will give you the count of rows

                            do
                            {   row = new Row();
                                row.Append(
                                ConstructCell(_arr[0], CellValues.String),
                                ConstructCell(_arr[1], CellValues.String),
                                ConstructCell(_arr[2], CellValues.String),
                                ConstructCell(_sb, CellValues.String,2U)
                                );

                            }
                            while (k > 0);
                           /* HERE I NEED TO ADD STYLE TO THE CELL. */
                       }
                    }

                    bl = true;
                }
            }
            catch (Exception ex)
            {
                bl = false;

                throw ex;
            }
            return bl;
        }

private static Stylesheet GenerateStylesheet(bool _valuecolour)
        {
            Stylesheet styleSheet = null;
            Fills fills = new Fills();            
            if (_valuecolour)
            {

                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 = "FFFFFF00" } })
                     { PatternType = PatternValues.Solid })
               );
            }
            else
            {

                 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 = "008000" } })
                   { PatternType = PatternValues.Solid }) // Index 2 - body
              );
            }
            CellFormats cellFormats = new CellFormats(
                    new CellFormat(), // default
                    new CellFormat(new Alignment() { Horizontal = HorizontalAlignmentValues.Left, Vertical = VerticalAlignmentValues.Top, WrapText = true })
                    { FontId = 0, FillId = 0, BorderId = 1, ApplyAlignment = true },
new CellFormat(new Alignment() { Horizontal = HorizontalAlignmentValues.Left, Vertical = VerticalAlignmentValues.Top, WrapText = true }){ FontId = 1, FillId = 2, BorderId = 1, ApplyFill = true }); // header

            styleSheet = new Stylesheet(fills, cellFormats);            
            return styleSheet;
        }


private static Cell ConstructCell(string value, CellValues dataType,uint styleIndex = 0)
        {
            return new Cell()
            {
                CellValue = new CellValue(value),
                DataType = new EnumValue<CellValues>(dataType),
                StyleIndex = styleIndex
            };
        }

1 个答案:

答案 0 :(得分:0)

以下是按预期工作的代码

在这里输入代码

#region ReadWriteExcel File
        public static bool ReadWriteExcel(string _sb, string _switchinput, bool _checkinitial)
        {
            string _str = string.Empty;
            bool _checkStatus = false;
            bool bl = false;
            String[] _arr;
            _arr = _switchinput.Split(',');
            int i = 0;
            string filepath = _directoryPath + DateTime.Now.ToString("dd.MM.yyyy") + ".xlsx";
            bl = (File.Exists(filepath) ? true : false);
            if (bl) // && _checkinitial
            {
                //_sb = string.Empty;
                //LogWrite("Just Before InsertRowExcel " + _switchinput);
                _checkStatus = InsertRowExcel(filepath, _sb.ToString(), _switchinput);
            }
            else
            {
                using (SpreadsheetDocument document = SpreadsheetDocument.Create(filepath, SpreadsheetDocumentType.Workbook))
                {
                    try
                    {
                        WorkbookPart workbookPart = document.AddWorkbookPart();
                        workbookPart.Workbook = new Workbook();

                        WorksheetPart worksheetPart = workbookPart.AddNewPart<WorksheetPart>();
                        WorkbookStylesPart stylePart = workbookPart.AddNewPart<WorkbookStylesPart>();
                        worksheetPart.Worksheet = new Worksheet();

                        Sheets sheets = workbookPart.Workbook.AppendChild(new Sheets());

                        Sheet sheet = new Sheet() { Id = workbookPart.GetIdOfPart(worksheetPart), SheetId = 1, Name = "SAN Switch Health Check" };
                        sheets.Append(sheet);
                        stylePart.Stylesheet = GenerateStylesheetDefault();
                        stylePart.Stylesheet.Save();
                        workbookPart.Workbook.Save();
                        SheetData sheetData = worksheetPart.Worksheet.AppendChild(new SheetData());
                        // Constructing header
                        Row row = new Row();

                        row.Append(
                            ConstructCell("Device_type", CellValues.String),
                            ConstructCell("Name", CellValues.String),
                            ConstructCell("IP Address", CellValues.String),
                            ConstructCell("Status", CellValues.String)
                          );

                        // Insert the header row to the Sheet Data
                        sheetData.AppendChild(row);

                        do
                        {
                            //for (int i = 0; i < _arr.Length - 1; i++)
                            //{
                            row = new Row();
                            row.Append(
                                ConstructCell(_arr[0], CellValues.String, 1U),
                                ConstructCell(_arr[1], CellValues.String, 1U),
                                ConstructCell(_arr[2], CellValues.String, 1U));//,
                                                                               //ConstructCell(_sb, CellValues.String,2U));
                                                                               //sheetData.AppendChild(row);
                        }
                        while (i > 0);

                        if (_sb != "Normal")
                        {
                            row.Append(
                              ConstructCell(_sb, CellValues.String, 2U));
                        }
                        else
                        {
                            row.Append(
                            ConstructCell(_sb, CellValues.String, 3U));
                        }
                        sheetData.AppendChild(row);
                        //stylePart.Stylesheet.Save();
                        worksheetPart.Worksheet.Save();

                        _checkStatus = true;
                    }
                    catch (Exception ex)
                    {
                        _checkStatus = false;
                        //LogWrite(ex.StackTrace.ToString());
                        throw ex;
                    }
                    document.Close();
                    document.Dispose();
                }

            }
            return _checkStatus;
        }
        private static Cell ConstructCell(string value, CellValues dataType, uint styleIndex = 0)
        {
            return new Cell()
            {
                CellValue = new CellValue(value),
                DataType = new EnumValue<CellValues>(dataType),
                StyleIndex = styleIndex
            };
        }

        public static bool InsertRowExcel(string filepath, string _sb, string _switchinput)
        {
            // LogWrite("InsertRowExcel " + _switchinput);

            int i = 0; int k = 0; bool bl = false; string[] _arr = _switchinput.Split(',');

            using (SpreadsheetDocument myDoc = SpreadsheetDocument.Open(filepath, true))
            {

                //Get workbookpart

                WorkbookPart workbookPart = myDoc.WorkbookPart;

                WorkbookStylesPart stylePart = workbookPart.WorkbookStylesPart;
                Row row = new Row();
                stylePart.Stylesheet = GenerateStylesheetDefault();
                stylePart.Stylesheet.Save();
                //then access to the worksheet part

                IEnumerable<WorksheetPart> worksheetPart = workbookPart.WorksheetParts;

                foreach (WorksheetPart WSP in worksheetPart)
                {//find sheet data
                    SheetData sheetData = WSP.Worksheet.Elements<SheetData>().First();


                    IEnumerable<Row> rows = sheetData.Elements<Row>(); // Get the row IEnumerator
                    i = (rows.Count()); // Will give you the count of rows                      
                                        /* HERE I NEED TO ADD STYLE TO THE CELL on condition. */
                    do
                    {
                        row = new Row();
                        row.Append(
                        ConstructCell(_arr[0], CellValues.String),
                        ConstructCell(_arr[1], CellValues.String),
                        ConstructCell(_arr[2], CellValues.String)
                        );
                        if (_sb != "Normal")
                        {
                            row.Append(
                              ConstructCell(_sb, CellValues.String, 2U));
                        }
                        else
                        {
                            row.Append(
                            ConstructCell(_sb, CellValues.String, 3U));
                        }

                        sheetData.Append(row);
                    } while (k > 0);
                }
                bl = true;
                myDoc.Close();
                myDoc.Dispose();
            }

            return bl;
        }
        public static Stylesheet GenerateStylesheetDefault()
        {
            Stylesheet stylesheet1 = new Stylesheet();
            Fonts fonts = new Fonts(
                new Font(
                    new FontSize() { Val = 11D },
                    new Color() { Theme = (UInt32Value)1U },
                     new FontName() { Val = "Calibri" },
                     new FontFamilyNumbering() { Val = 2 },
                     new FontScheme() { Val = FontSchemeValues.Minor }
                    )
                );

            Borders borders = new Borders(
                new Border(
                    new LeftBorder(),
                    new RightBorder(),
                    new TopBorder(),
                    new BottomBorder(),
                    new DiagonalBorder())
                );
            Fills fills = new Fills();

            fills = new Fills(
                new Fill(
                    new PatternFill() { PatternType = PatternValues.None }), //0
                new Fill(
                    new PatternFill() { PatternType = PatternValues.Gray125 }),//1
                new Fill(
                    new PatternFill(
                        new ForegroundColor { Rgb = new HexBinaryValue() { Value = "FFFFFF00" } }) //2 -yellow
                    { PatternType = PatternValues.Solid }),
                new Fill(
                    new PatternFill(
                        new ForegroundColor { Rgb = new HexBinaryValue() { Value = "FF008000" } })// 3 -green
                    { PatternType = PatternValues.Solid })
                );

            CellStyleFormats cellStyleFormats = new CellStyleFormats(
                new CellFormat() { NumberFormatId = (UInt32Value)0U, FontId = (UInt32Value)0U, FillId = (UInt32Value)0U, BorderId = (UInt32Value)0U }
                );

            CellFormats cellFormats = new CellFormats(
                new CellFormat() { NumberFormatId = (UInt32Value)0U, FontId = (UInt32Value)0U, FillId = (UInt32Value)0U, BorderId = (UInt32Value)0U, FormatId = (UInt32Value)0U },
                 new CellFormat(
                     new Alignment() { Horizontal = HorizontalAlignmentValues.Left, Vertical = VerticalAlignmentValues.Top, WrapText = true })
                 { FontId = 0, FillId = 0, BorderId = 0, ApplyAlignment = true },
                 new CellFormat(
                     new Alignment() { Horizontal = HorizontalAlignmentValues.Left, Vertical = VerticalAlignmentValues.Top, WrapText = true })
                 { FontId = 0, FillId = 2, BorderId = 0, ApplyFill = true },
                new CellFormat(
                     new Alignment() { Horizontal = HorizontalAlignmentValues.Left, Vertical = VerticalAlignmentValues.Top, WrapText = true })
                { FontId = 0, FillId = 3, BorderId = 0, ApplyFill = true }
                );

            stylesheet1.Append(fonts);
            stylesheet1.Append(fills);
            stylesheet1.Append(borders);
            stylesheet1.Append(cellStyleFormats);
            stylesheet1.Append(cellFormats);
            return stylesheet1;
        }
        #endregion