我正在尝试使用OpenXML在Excel中创建命名范围。我能够在DefinedNames集合中添加DefinedName,但似乎没有做任何事情。我注意到在ExtendedFileProperties中有一个位置,其中保存了范围的名称,一个名为“TitlesOfParts”的结构。我尝试在那里添加一个条目,但这会导致excel抛出错误,并且不会创建命名范围。这是我正在使用的代码:
public void AddNamedRange(string pNamedRangeRef, string pNamedRangeName)
{
DefinedName _definedName = new DefinedName() { Name = pNamedRangeName, Text = pNamedRangeRef };
_workbook.Descendants<DocumentFormat.OpenXml.Spreadsheet.DefinedNames>().First().Append(_definedName);
DocumentFormat.OpenXml.VariantTypes.VTLPSTR _t = new DocumentFormat.OpenXml.VariantTypes.VTLPSTR() { Text = pNamedRangeName };
_spreadsheet.ExtendedFilePropertiesPart.Properties.TitlesOfParts.VTVector.Append(_t);
_spreadsheet.ExtendedFilePropertiesPart.Properties.TitlesOfParts.VTVector.Size++;
}
答案 0 :(得分:2)
使用Open XML SDK 2.0 Productivity Tool for Microsoft Office
来定义全局/工作簿范围的命名范围非常简单:
DefinedNames definedNamesCol = new DefinedNames(); //Create the collection
DefinedName definedName = new DefinedName()
{ Name = "test", Text="Sheet1!$B$2:$B$4" }; // Create a new range
definedNamesCol.Append(definedName); // Add it to the collection
workbook.Append(definedNamesCol); // Add collection to the workbook
答案 1 :(得分:1)
以下代码为我做了诀窍。在此之后,我也能够看到excel中的名称范围。
var wbPart = document.WorkbookPart;
Workbook workbook = wbPart.Workbook;
DefinedName definedName1 = new DefinedName { Name = "ColumnRange",Text = "Sheet1!$A$1:$I$1"};
DefinedName definedName2 = new DefinedName { Name = "RowRange", Text = "Sheet1!$A$1:$A$15"};
if (workbook.DefinedNames == null)
{
DefinedNames definedNames1 = new DefinedNames();
definedNames1.Append(definedName1);
definedNames1.Append(definedName2);
workbook.DefinedNames = definedNames1;
}