excel 使用OpenXML SDK 2.5对电子表格文档应用格式设置不起作用

lp0sw83n  于 7个月前  发布在  其他
关注(0)|答案(1)|浏览(96)

我正在使用OpenXML SDK 2.5创建一个Excel文件--在OpenXML行话中也称为Excel表格文档--然后对单元格应用某种格式。
当在Excel中打开生成的文件时,这种格式设置根本不起作用,尽管生成的文件通过了验证器,包括我在代码中使用的验证器和OpenXML SDK 2.5 Productivity Tool验证器。
我甚至仔细检查并手动复制和粘贴工作版本中的XML片段(通过将生成的文件的副本保存在Excel中创建)到生成的文件中,但大多数情况下只会导致无效文件。
生成的XML中的所有内容看起来都像它应该的那样,从工作表XML数据到样式表XML数据的正确引用,以及用于定义样式的正确格式化的XML(在本例中,只是将单元格内容更改为粗体)。
经过几个小时的故障排除和与最好和最聪明的AI机器人聊天(聊天GPT 4),我终于找到了问题。
请看下面我的回答。

ebdffaop

ebdffaop1#

实际上有两件事可能会让你绊倒,特别是如果你只依赖人工智能的建议。
OpenXML标准要求在一个 * 样式表 * 中至少有一个 FontsBordersFills 对象才是有效的,省略其中任何一个都将导致Excel无法打开文件。我发现AI有时不愿意解释这一点,而且在阅读文档时并不明显(至少对我来说不是)。
然而,导致我的问题的是,我在文档中找不到任何信息,AI从未提到-并且仍然通过了上面提到的验证,我需要在样式表中使用默认的 CellFormat 对象,即使我从未引用它。
我不能分享我所有的代码,因为它在添加格式时做了很多事情,但这是它的要点。

// Create a CellFormats collection if it doesn't exist
stylesheet.CellFormats ??= new CellFormats();
stylesheet.CellFormats.Count ??= 0;

// Create a default CellFormat that we're not using but is required for the rest of the formatting to work
CellFormat defaultCellFormat = new CellFormat();
stylesheet.CellFormats.Append(defaultCellFormat);

// Create a new CellFormat that we actually use
var cellFormat = new CellFormat();

// Add all the formatting to the CellFormat
// Your code here...

// Append the new CellFormat object to the CellFormats collection and get its index
stylesheet.CellFormats.Append(cellFormat);
stylesheet.CellFormats.Count = (uint)stylesheet.CellFormats.ChildElements.Count;
uint formatIndex = (uint)stylesheet.CellFormats.ToList().IndexOf(cellFormat);

// Apply the formatting to the current cell by setting its StyleIndex property
cell.StyleIndex = formatIndex;

字符串
这可能是我的代码所独有的,但希望这能为其他人省去费力阅读一页又一页OpenXML文档的麻烦。

相关问题