Last active
June 13, 2022 18:51
-
-
Save zhangw/4601021 to your computer and use it in GitHub Desktop.
Use openxml to create the new cellformat and apply it to cell.
Use openxml to modify the cellformat of cell.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var styleSheet = document.WorkbookPart.WorkbookStylesPart.Stylesheet; | |
Fill fill = new Fill() { PatternFill = new PatternFill { ForegroundColor = new ForegroundColor { Rgb = fgcolor }, PatternType = PatternValues.Solid } }; | |
styleSheet.Fills.Append(fill); | |
//or use the method Count(),not need to plus 1,but slowly. | |
var fid = styleSheet.Fills.Count++; | |
CellFormat cellFormat = null; | |
if (theCell.StyleIndex.HasValue) | |
{ | |
var originalCellFormat = document.WorkbookPart.WorkbookStylesPart.Stylesheet.CellFormats.ToList()[(int)theCell.StyleIndex.Value] as CellFormat; | |
//copy the original cellformat data to the new cellformat | |
if (originalCellFormat != null) | |
{ | |
cellFormat = new CellFormat(originalCellFormat.OuterXml); | |
} | |
else | |
{ | |
cellFormat = new CellFormat(); | |
} | |
} | |
else | |
{ | |
cellFormat = new CellFormat(); | |
} | |
cellFormat.FillId = (UInt32)fid; | |
styleSheet.CellFormats.Append(cellFormat); | |
var theStyleIndex = styleSheet.CellFormats.Count++; | |
theCell.StyleIndex = new UInt32Value { Value = (UInt32)theStyleIndex }; | |
document.WorkbookPart.WorkbookStylesPart.Stylesheet.Save(); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var theStyleIndex = theCell.StyleIndex; | |
var fillId = ((document.WorkbookPart.WorkbookStylesPart.Stylesheet.CellFormats.ToList()[(int)theStyleIndex.Value]) as CellFormat).FillId.Value; | |
var fgcolorobj = document.WorkbookPart.WorkbookStylesPart.Stylesheet.Fills.ToList()[(int)fillId].Descendants<PatternFill>().First(); | |
if (fgcolorobj != null) | |
{ | |
if (fgcolorobj.ForegroundColor != null) | |
{ | |
fgcolorobj.ForegroundColor.Rgb = new HexBinaryValue { Value = fgcolor }; | |
} | |
else | |
{ | |
fgcolorobj.ForegroundColor = new ForegroundColor { Rgb = fgcolor }; | |
} | |
} | |
document.WorkbookPart.WorkbookStylesPart.Stylesheet.Save(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment