gpt4 book ai didi

c# - 使用 OpenXML 将 % 数字格式应用于单元格值

转载 作者:IT王子 更新时间:2023-10-29 04:41:29 26 4
gpt4 key购买 nike

我想使用 open XML C# 应用 %(百分比)数字格式

我有数值 3.6,我想在 excel 中将该数字显示为 `3.6%。

我该如何实现?

最佳答案

  WorkbookStylesPart sp = workbookPart.AddNewPart<WorkbookStylesPart>();

创建样式表,

 sp.Stylesheet = new Stylesheet();

创建一个编号格式,

sp.Stylesheet.NumberingFormats = new NumberingFormats();
// #.##% is also Excel style index 1


NumberingFormat nf2decimal = new NumberingFormat();
nf2decimal.NumberFormatId = UInt32Value.FromUInt32(3453);
nf2decimal.FormatCode = StringValue.FromString("0.0%");
sp.Stylesheet.NumberingFormat.Append(nf2decimal);

创建单元格格式并应用编号格式 id

cellFormat = new CellFormat();
cellFormat.FontId = 0;
cellFormat.FillId = 0;
cellFormat.BorderId = 0;
cellFormat.FormatId = 0;
cellFormat.NumberFormatId = nf2decimal.NumberFormatId;
cellFormat.ApplyNumberFormat = BooleanValue.FromBoolean(true);
cellFormat.ApplyFont = true;

//append cell format for cells of header row
sp.Stylesheet.CellFormats.AppendChild<CellFormat>(cellFormat);


//update font count
sp.Stylesheet.CellFormats.Count = UInt32Value.FromUInt32((uint)sp.Stylesheet.CellFormats.ChildElements.Count);


//save the changes to the style sheet part
sp.Stylesheet.Save();

并且当您将值附加到单元格时,在此处使用以下中心代码 onversion 并应用样式索引在我的例子中,我有三个样式索引,因此第 3 个是我的百分比样式索引,即 2,因为索引从 0 开始

string val = Convert.ToString(Convert.ToDecimal(value)/100);
Cell cell = new Cell();
cell.DataType = new EnumValue<CellValues>(CellValues.Number);
cell.CellValue = new CellValue(val);
cell.StyleIndex = 2;
row.Append(cell);

关于c# - 使用 OpenXML 将 % 数字格式应用于单元格值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7872116/

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