How to set cells' background?

前端 未结 2 601
时光说笑
时光说笑 2021-01-12 03:51

How to set the background of several cells within a row (or of a whole row) in OpenXml?

Having read several articles:

  1. Coloring cells in excel sheet usi
2条回答
  •  失恋的感觉
    2021-01-12 04:57

    In the end I changed my mind to use cell background and used fonts. Thanks to answer by foson in SO Creating Excel document with OpenXml sdk 2.0 I managed to add a new Font and a new CellFormat, having preserved the original cell's formatting (i.e. having changed the font color only):

    SpreadsheetDocument doc = SpreadsheetDocument.Open("1.xlsx", true);
    Sheet sheet = (Sheet)doc.WorkbookPart.Workbook.Sheets.FirstOrDefault();
    WorksheetPart worksheetPart = (WorksheetPart)doc.WorkbookPart
                                                    .GetPartById(sheet.Id);
    Worksheet worksheet = worksheetPart.Worksheet;
    
    WorkbookStylesPart styles = doc.WorkbookPart.WorkbookStylesPart;
    Stylesheet stylesheet = styles.Stylesheet;
    CellFormats cellformats = stylesheet.CellFormats;
    Fonts fonts = stylesheet.Fonts;
    
    UInt32 fontIndex = fonts.Count;
    UInt32 formatIndex = cellformats.Count;
    
    Cell cell = GetCell(worksheet, "A", 19);
    cell.CellValue = new CellValue(DateTime.Now.ToLongTimeString());
    cell.DataType = new EnumValue(CellValues.String);
    
    CellFormat f = (CellFormat)cellformats.ElementAt((int)cell.StyleIndex.Value);
    
    var font = (Font)fonts.ElementAt((int)f.FontId.Value);
    var newfont = (Font)font.Clone();
    newfont.Color = new Color() { Rgb = new HexBinaryValue("ff0000") };
    fonts.Append(newfont);
    
    CellFormat newformat = (CellFormat)f.Clone();
    newformat.FontId = fontIndex;
    cellformats.Append(newformat);
    
    stylesheet.Save();
    
    cell.StyleIndex = formatIndex;
    doc.Close();
    

提交回复
热议问题