我想使用open XML C#
应用%(百分比)数字格式我有数值3.6,我想在excel中显示该数字为3.6%。
我如何实现这一目标?
答案 0 :(得分:24)
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开始
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);
答案 1 :(得分:15)
不幸的是,没有直截了当的答案。如果您下载适用于Microsoft Office的OpenXML Productivity Tool,您可以剖析一个简单的电子表格,并查看它如何格式化该数字。要做到你想要的,你需要:
呼!
通常更好的选择是在http://closedxml.codeplex.com/(可怕名称)查看ClosedXML。它是一个开源(不是GPL! - 检查许可证)库,它在OpenXML上放置了有用的扩展。要格式化工作表的单元格,您需要执行以下操作:
worksheet.Cell(row, col).Value = "0.036";
worksheet.Cell(row, col).Style.NumberFormat.Format = "0.0%";
(来自http://closedxml.codeplex.com/wikipage?title=Styles%20-%20NumberFormat&referringTitle=Documentation)
<强>更新强> ClosedXML已移至https://github.com/ClosedXML/ClosedXML
的GitHub答案 2 :(得分:4)
Excel包含以各种方式格式化字符串的预定义格式。单元格元素上的s
属性将引用一种样式,该样式将引用与您想要的百分比格式相对应的数字格式。有关详细信息,请参阅此question/answer。
以下是您需要创建的CellFormat对象,以便将0.00%蒙版应用于您的数字。在这种情况下,您需要预定义的格式编号10或0.00%:
CellFormat cellFormat1 = new CellFormat(){ NumberFormatId = (UInt32Value)10U, FontId = (UInt32Value)0U, FillId = (UInt32Value)0U, BorderId = (UInt32Value)0U, FormatId = (UInt32Value)0U, ApplyNumberFormat = true };
以下是将CellFormat插入工作簿的快速方法:
CellFormats cellFormats = workbookPart.WorkbookStylesPart.Stylesheet.Elements<CellFormats>().First();
cellFormats.Append(cellFormat);
uint styleIndex = (uint)cellFormats.Count++;
然后,您需要获取其中包含3.6的单元格,并将其s
属性(StyleIndex)设置为新插入的单元格格式:
Cell cell = workSheetPart.Worksheet.Descendants<Cell>().SingleOrDefault(c => cellAddress.Equals("A1"));
cell.StyleIndex = styleIndex;
答案 3 :(得分:1)
您可以通过简单的方式完成此操作。如果你想在单个单元格上应用它,那么就这样做,
worksheet.Cell(9, 10).Style.NumberFormat.Format = "#,##0.00\\%";
如果你想在一系列细胞上应用它,那么就这样做,
worksheet.Range(9, 10, 15, 10).Style.NumberFormat.Format = "#,##0.00\\%";
您还可以找到更多格式Here,您也可以在Excel中找到相同的格式。