Skip to content

Instantly share code, notes, and snippets.

@zhangw
Last active June 13, 2022 18:51
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zhangw/4601021 to your computer and use it in GitHub Desktop.
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.
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();
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