gpt4 book ai didi

c# - 在openxml中为Excel添加样式

转载 作者:太空宇宙 更新时间:2023-11-03 15:30:13 25 4
gpt4 key购买 nike

我想在我打开写文本的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;

错误:

Object not set to instance of an object.

当我在代码上添加 watch 时:

spreadSheet.WorkbookPart.WorkbookStylesPart.Stylesheet;

我发现:spreadSheet.WorkbookPart.WorkbookStylesPart 为空

请帮助我如何为单元格添加前景色

最佳答案

也许缺少 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;
}

关于c# - 在openxml中为Excel添加样式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34011985/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com