c# - 在 C# 中使用 OpenXML 应用数字格式时遇到问题

标签 c# openxml

我正在尝试使用 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/

相关文章:

c# - 在 C# .NET 应用程序的整个生命周期中使用 DecisionTree

c# - 将注册表中的版本号转换为System.Version?

mysql - 无法在 SQL 中使用 OPENXML 查询 XML 文件

openxml - 无法使用 OpenXml 为 word 添加项目符号

使用 Open XML SDK 保护 Excel 文件密码

c# - 带有 ASP.NET MVC 3 的 Blueimp 多文件 uploader

c# - ASP.NET MVC Razor View 建立在两个对象的 Viewmodel 之上。架构建议如何更新引用两个对象的计算字段

c# - 将 Field<> 与 Linq to SQL 结合使用

c# - 为什么在此示例中附加自动筛选会损坏我的 excel 文件?

xml - 如何自动将 Doc/Docx 转换为单个 XML 文件?