在openxml中向Excel添加样式 [英] Add style to Excel in openxml
本文介绍了在openxml中向Excel添加样式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想在打开的Excel文档中设置文本的原色.
I want to set forecolor of the text in the excel document which I open to write the text.
为此,我尝试了:
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();
但这在第一行给了我错误:
But it gives me error on the first line :
var stylesheet1 = spreadSheet.WorkbookPart.WorkbookStylesPart.Stylesheet;
错误:
对象未设置为对象的实例.
Object not set to instance of an object.
当我添加代码监视时:
spreadSheet.WorkbookPart.WorkbookStylesPart.Stylesheet;
我发现:spreadSheet.WorkbookPart.WorkbookStylesPart
为空
请帮助我如何为单元格添加原色
Please help me how can i add forecolor to cell
推荐答案
也许SpreadsheetDocument的初始化丢失了吗?
Perhaps the initialization of SpreadsheetDocument is missing?
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;
}
这篇关于在openxml中向Excel添加样式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文