使用 OpenXML SDK 2.5 将格式应用于 SpreadsheetDocument 不起作用

问题描述 投票:0回答:1

我正在使用 OpenXML SDK 2.5 创建一个 Excel 文件(在 OpenXML 术语中又称为 SpreadsheetDocument),然后对单元格应用某种格式。

在 Excel 中打开生成的文件时,尽管生成的文件通过了验证器(我在代码中使用的验证器和 OpenXML SDK 2.5 Productivity Tool 验证器),但这种格式根本不起作用。

我什至手动将工作版本中的 XML 片段(通过在 Excel 中保存生成文件的副本创建)手动复制并粘贴到我生成的文件中,但这大多只会导致无效文件。

生成的 XML 中的所有内容看起来都符合预期,从工作表 XML 数据到样式表 XML 数据的正确引用,以及正确格式化的 XML 来定义样式(在本例中,只需将单元格内容更改为粗体)。

经过数小时的故障排除并与最优秀、最聪明的 AI 机器人聊天(聊天 GPT 4)后,我终于解决了问题。

请参阅下面我的回答。

c# excel openxml openxml-sdk
1个回答
0
投票

实际上有两件事可能会让你陷入困境,尤其是如果你只依赖人工智能建议的话。

OpenXML 标准要求 Stylesheet 中至少有一个 FontsBordersFills 对象才有效,省略其中任何一项都将导致 Excel 无法打开文件。我发现这是人工智能有时不愿意解释的事情,并且在阅读文档时并不明显(至少对我来说不是)。

但是,导致我的问题的原因是,我在文档中找不到任何相关信息,并且 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 文档的麻烦。 :)

© www.soinside.com 2019 - 2024. All rights reserved.