我想使用开放的 XML C#应用%(百分比)数字格式 我有数值3.6,我想在Excel中显示该数字为3.6%. 我如何实现这一目标? WorkbookStylesPart sp = workbookPart.AddNewPartWorkbookStylesPart(); 创建样式表, sp.
我有数值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();
当您将值附加到单元格时,具有以下中心代码hereonversion并应用样式索引
在我的情况下我有三个样式索引,因此3个是我的百分比样式索引,即索引从0开始的2
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);