I am trying to create named ranges in Excel with OpenXML. I am able to add a DefinedName in the DefinedNames collection, but that does not seem to do anything. I noticed a place in the ExtendedFileProperties where the names of ranges are being saved, a structure called "TitlesOfParts". I have tried adding an entry in there but that causes excel to throw an error and the named range is not created. Here is the code I am using:
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++;
}
NuGet Package DocumentFormat. OpenXml. The Open XML SDK provides tools for working with Office Word, Excel, and PowerPoint documents. It supports scenarios such as: - High-performance generation of word-processing documents, spreadsheets, and presentations.
xls files. Excel for . NET can load and save data and formatting information in OpenXml files; however, formulas are not loaded or saved. They are copied in BIFF format as opaque.
Using the Open XML SDK 2.0 Productivity Tool for Microsoft Office
, to define a global/workbook-wide named range is pretty easy:
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
The below code did the trick for me. After this I was able to see the name ranges in excel also.
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With