我正在尝试使用 OpenXML 在我生成的 excel 文档中获取一列,以便以友好的方式为 12 位 UPC 设置格式。
为了实现这一点,我使用了以下代码(基于此 question ):
var sp = workbookpart.AddNewPart<WorkbookStylesPart>();
sp.Stylesheet = new Stylesheet {NumberingFormats = new NumberingFormats(), CellFormats = new CellFormats()};
var upcFormatting = new NumberingFormat {NumberFormatId = 164, FormatCode = "000000000000"};
var upcCellFormat = new CellFormat
{
NumberFormatId = upcFormatting.NumberFormatId,
FontId = 0U,
FillId = 0U,
BorderId = 0U,
FormatId = 0U,
ApplyNumberFormat = BooleanValue.FromBoolean(true)
};
sp.Stylesheet.NumberingFormats.AppendChild(upcFormatting);
sp.Stylesheet.CellFormats.AppendChild(upcCellFormat);
sp.Stylesheet.NumberingFormats.Count++;
sp.Stylesheet.CellFormats.Count++;
var styleIndex = sp.Stylesheet.CellFormats.Count;
workbookpart.Workbook.Save();
不幸的是,上面的代码生成了一个 excel 认为损坏的样式表,该表如下所示:
<?xml version="1.0" encoding="UTF-8"?>
<x:styleSheet xmlns:x="http://schemas.openxmlformats.org/spreadsheetml/2006/main">
<x:numFmts count="1">
<x:numFmt formatCode="000000000000" numFmtId="164"/>
</x:numFmts>
<x:cellXfs count="1">
<x:xf numFmtId="164" applyNumberFormat="1" xfId="0" borderId="0" fillId="0" fontId="0"/>
</x:cellXfs>
</x:styleSheet>
如果有人可以提供关于如何获得一个有效的样式表的见解,该样式表使用允许仅使用 OpenXML 显示 12 位数字的编号格式生成(不能使用围绕它构建的任何框架,例如 ClosedXML)我将不胜感激。
谢谢,
最佳答案
您缺少样式表中的默认样式。添加以下行(必须在第一行)并将 cellXfs 计数更改为 2。不要忘记更新您的工作表以使用样式“2”而不是“1”。
<xf numFmtId="0" fontId="0" fillId="0" borderId="0" xfId="0"/>
关于c# - 在 C# 中使用 OpenXML 应用数字格式时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9929339/