在openxml中添加样式到Excel

我想在我打开的excel文件中设置文本的前景写文本。

为此我尝试了:

var stylesheet1 = spreadSheet.WorkbookPart.WorkbookStylesPart.Stylesheet; Fills fills1 = new Fills() { Count = (UInt32Value)5U }; Fill fill5 = new Fill(); PatternFill patternFill5 = new PatternFill() { PatternType = PatternValues.Solid }; ForegroundColor foregroundColor3 = new ForegroundColor() { Rgb = "#FF0000" }; patternFill5.Append(foregroundColor3); fill5.Append(patternFill5); fills1.Append(fill5); stylesheet1.Fills.Append(fills1); var fid = stylesheet1.Fills.Count++; wbsp.Stylesheet = stylesheet1; Row excelRow; excelRow = new Row(); excelRow.RowIndex = 0; Cell cell = new Cell() { //create the cell reference of format A1, B2 etc //CellReference = Convert.ToString(Convert.ToChar(65)), CellReference = "A1", DataType = CellValues.String }; CellValue cellValue = new CellValue(); cellValue.Text = "*"; //add the value to the cell cell.Append(cellValue); CellFormat cellFormat = null; if (cell.StyleIndex.HasValue) { var originalCellFormat = spreadSheet.WorkbookPart.WorkbookStylesPart.Stylesheet.CellFormats.ToList()[(int)cell.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; stylesheet1.CellFormats.Append(cellFormat); var theStyleIndex = stylesheet1.CellFormats.Count++; cell.StyleIndex = new UInt32Value { Value = (UInt32)theStyleIndex }; spreadSheet.WorkbookPart.WorkbookStylesPart.Stylesheet.Save(); 

但是它在第一行中给了我错误:

 var stylesheet1 = spreadSheet.WorkbookPart.WorkbookStylesPart.Stylesheet; 

错误:

对象未设置为对象的实例。

当我添加一个代码的手表:

 spreadSheet.WorkbookPart.WorkbookStylesPart.Stylesheet; 

我发现: spreadSheet.WorkbookPart.WorkbookStylesPart为空

请帮助我如何添加forecolor到单元格

也许SpreadsheetDocument的初始化丢失?

 using (SpreadsheetDocument document = SpreadsheetDocument.Create(filePath + ".xlsx", SpreadsheetDocumentType.Workbook)) { WorkbookPart workbookPart = document.AddWorkbookPart(); workbookPart.Workbook = new Workbook(); WorksheetPart worksheetPart = workbookPart.AddNewPart<WorksheetPart>(); worksheetPart.Worksheet = new Worksheet(); WorkbookStylesPart workStylePart = workbookPart.AddNewPart<WorkbookStylesPart>(); workStylePart.Stylesheet = new Stylesheet(); var stylesheet1 = document.WorkbookPart.WorkbookStylesPart.Stylesheet; }