当我设置pageSetup时,OpenXML破坏了excel文件
我有一个从我的程序DevExpress创build的Excel文件。 我需要在这个文件中添加水平中断页面,但我不能,因为我的DevExpress版本不处理它。 所以我在一个单独的类中使用OpenXML来检索生成的excel文件,以便添加水平中断页面。
DevExpress生成后,我的文件看起来像这样:
所以它有6页。 我想有这个,而不是:
为了在单独的工作表上打印每个选项卡。
所以我使用openXML中的PageSetup来定义我的excel文件的宽度和高度:
private void InsertPageBreaks() { //uint columnIndex = 17U; uint rowIndex = 42; SpreadsheetDocument sd = SpreadsheetDocument.Open("c:\\temp\\ExcelExport1.xlsx", true); try { WorkbookPart workbookPart = sd.WorkbookPart; WorksheetPart worksheetPart = workbookPart.WorksheetParts.Last(); // Uncomment the following line to insert row page breaks. InsertHorizontalPageBreak(rowIndex, worksheetPart); PageSetup pageSetup = new PageSetup() {FitToHeight = 2, FitToWidth = 1}; worksheetPart.Worksheet.AppendChild(pageSetup); } finally { if (sd != null) ((IDisposable)sd).Dispose(); } }
但经过处理后,当我尝试打开文件时出现错误“抱歉,我们发现有一些内容的问题[…]”。
你们有什么想法如何帮助我吗?
非常感谢 !
很难说没有看到文件,但我很确定这是因为你的元素的顺序发生。
ECMA-376标准定义了Excel文档的模式,其中一部分是Worksheet
定义(3900页)。 该定义太大,无法完整粘贴,但有关PageSetup
的部分如下所示:
<xsd:element name = "pageMargins" type="CT_PageMargins" minOccurs="0" maxOccurs="1"/> <xsd:element name = "pageSetup" type="CT_PageSetup" minOccurs="0" maxOccurs="1"/> <xsd:element name = "headerFooter" type="CT_HeaderFooter" minOccurs="0" maxOccurs="1"/> <xsd:element name = "rowBreaks" type="CT_PageBreak" minOccurs="0" maxOccurs="1"/> <xsd:element name = "colBreaks" type="CT_PageBreak" minOccurs="0" maxOccurs="1"/> <xsd:element name = "customProperties" type="CT_CustomProperties" minOccurs="0" maxOccurs="1"/> <xsd:element name = "cellWatches" type="CT_CellWatches" minOccurs="0" maxOccurs="1"/> <xsd:element name = "ignoredErrors" type="CT_IgnoredErrors" minOccurs="0" maxOccurs="1"/> <xsd:element name = "smartTags" type="CT_SmartTags" minOccurs="0" maxOccurs="1"/> <xsd:element name = "drawing" type="CT_Drawing" minOccurs="0" maxOccurs="1"/> <xsd:element name = "drawingHF" type="CT_DrawingHF" minOccurs="2222 0" maxOccurs="1"/> <xsd:element name = "picture" type="CT_SheetBackgroundPicture" minOccurs="0" maxOccurs="1"/> <xsd:element name = "oleObjects" type="CT_OleObjects" minOccurs="0" maxOccurs="1"/> <xsd:element name = "controls" type="CT_Controls" minOccurs="0" maxOccurs="1"/> <xsd:element name = "webPublishItems" type="CT_WebPublishItems" minOccurs="0" maxOccurs="1"/> <xsd:element name = "tableParts" type="CT_TableParts" minOccurs="0" maxOccurs="1"/> <xsd:element name = "extLst" type="CT_ExtensionList" minOccurs="0" maxOccurs="1"/>
由于Worksheet
被定义为一个序列,顺序是重要的。 看看你的截图,看起来你有一个Header
必须在 PageSetup
之后 ,但是你的代码将PageSetup
添加到Worksheet
的末尾。
有关如何将项目添加到正确位置的示例,请参阅我的答案为什么在此示例中添加AutoFilter会破坏我的Excel文件?