简体   繁体   English

如何使用OpenXML设置Excel“打印标题”

[英]How to set Excel “Print Titles” with OpenXML

How can I set the "Print Titles" property of a spreadsheet with OpenXML, to have a row show at the top of every printed page? 如何使用OpenXML设置电子表格的“打印标题”属性,以在每个打印页面的顶部显示一行?

打印标题界面

The property is directly saved in the SpreadsheetPrintingParts object, however, this doesn't appear to be fully integrated into OpenXML as of yet, and requires passing a base64 string in to the variable. 该属性直接保存在SpreadsheetPrintingParts对象中,但是, SpreadsheetPrintingParts ,该属性似乎尚未完全集成到OpenXML中,并且需要将base64字符串传递给该变量。 ( see here ) The content of this string appears to be tied to the machine the file is opened on, which didn't work for my implementation - I wasn't able to create a non-corrupt file through SpreadsheetPrintingParts.FeedData() . 请参阅此处 )此字符串的内容似乎与打开文件的机器有关,这对于我的实现不起作用-我无法通过SpreadsheetPrintingParts.FeedData()创建非损坏的文件。

Instead, I found this post which stated giving the row the defined name "Print_Titles" has the same effect. 取而代之的是,我发现这篇文章说给行定义名称“ Print_Titles”具有相同的效果。 I was then able to create a defined name through OpenXML with the following code: 然后,我可以使用以下代码通过OpenXML创建定义的名称:

public void SetPrintTitleRows(int startRowIndex, int? endRowIndex = null)
        {
            var localSheetId = _localsheetId++;    //LocalSheetIds are 0-indexed.

            var definedName = new DefinedName
            {
                Name = "_xlnm.Print_Titles",
                LocalSheetId = localSheetId,
                Text = String.Format("\'{0}\'!${1}:${2}", _sheetName, startRowIndex, endRowIndex ?? startRowIndex)
            };

            if (_workbookPart.Workbook.DefinedNames == null)
            {
                var definedNamesCol = new DefinedNames();
                _workbookPart.Workbook.Append(definedNamesCol);
            }

            _workbookPart.Workbook.DefinedNames.Append(definedName);
        }

Points to note: 注意事项:

  1. DefinedName.LocalSheetId is zero-indexed, as opposed to Sheet.Id which is 1-indexed DefinedName.LocalSheetId的索引为零,而Sheet.Id的索引为1。
  2. DefinedNames is once per workbook, but can contain multiple DefinedName objects for different sheets. 每个工作簿一次, DefinedNames ,但可以包含多个用于不同工作表的DefinedName对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM