在OpenXML中设置DefinedNames,为Excel中的所有工作表设置打印标题

我的最终目标是以编程方式为我的文档中的所有工作表设置Excel的“打印标题”值。

最初我尝试着使用SpreadsheetPrintingParts对象( 基于这个问题 ) – 但是,这需要生成一个基本的64string,它看起来必须来自一个现有的文件。 (我从头开始生成电子表格。)

这篇文章然后告诉我,我可以将“Print_Titles”设置为我需要的行上定义的名称。 我一直试图以编程方式做,但这似乎破坏了我的所有文件。

我的代码:

  var definedNamesCol = new DefinedNames(); //Create the collection var definedName = new DefinedName() { Name = "_xlnm.Print_Titles", Text = "\'SheetName\'!$2:$2", LocalSheetId = (UInt32) (_nextSheetId - 1) }; // Create a new range definedNamesCol.Append(definedName); // Add it to the collection _workbookPart.Workbook.Append(definedNamesCol); 

我也看过OpenXML的生产力工具,它表明:(基本上相同)

  DefinedNames definedNames1 = new DefinedNames(); DefinedName definedName1 = new DefinedName(){ Name = "_xlnm.Print_Titles", LocalSheetId = (UInt32Value)0U }; definedName1.Text = "\'SheetName\'!$2:$2"; definedNames1.Append(definedName1) 

我也尝试在Xlm上设置Xlm属性,但是文件随后打开时出现一个错误,它包含了Macro-Free文件中的macros,这不是我想要的。

我在workbook.xml中生成的(简化)版本:

 <?xml version="1.0" encoding="utf-8"?> <x:workbook xmlns:x="http://schemas.openxmlformats.org/spreadsheetml/2006/main"> <x:sheets> <x:sheet name="ABBEY" sheetId="1" r:id="R2f5447238bc94fa4" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" /> </x:sheets> <x:definedNames> <x:definedName name="_xlnm.Print_Titles" localSheetId="0">'SheetName'!$2:$2</x:definedName> </x:definedNames> </x:workbook> 

有没有更好的方法来解决这个问题? 或者我的意图是对的,这是对其他方法的误解。

上面的代码是在一个CreateWorksheet方法中,所以被称为每个工作表。 在生成的workbook.xml文件中,创build多个definedNames对象时,应该只有一个包含多个definedNames definedNames对象。

我使用这个代码解决了这个问题:

  var definedName = new DefinedName() { Name = "_xlnm.Print_Titles", Text = "\'Sheet Name\'!$2:$2", LocalSheetId = (UInt32) (_nextSheetId - 1) }; // Create a new range if (_workbookPart.Workbook.DefinedNames == null) { var definedNamesCol = new DefinedNames(); _workbookPart.Workbook.Append(definedNamesCol); } _workbookPart.Workbook.DefinedNames.Append(definedName); // Add it to the collection