0

In my current project I want to find the ranges of a worksheet, but the lookupWorksheet.Cells.Ranges property contains no elements while Workbook.Worksheets.GetNamedRanges() does.

My initial code was

var sheetRanges = worksheet.Cells.Ranges.Cast<Range>().ToList();

I had to change it to the more complicated

var sheetRanges = worksheet.Workbook.Worksheets.GetNamedRanges();
if (sheetRanges != null) {
    sheetRanges = sheetRanges.Where(range => range.Worksheet == worksheet).ToArray();
}

Does it matter that the range was created by code earlier?
Do I have to 'commit' that range somewhere maybe?

Boris Callens
  • 90,659
  • 85
  • 207
  • 305

2 Answers2

0

Please note, you will have to set the Range.Name property to make your range appear in the Workbook.Worksheets.GetNamedRanges() method.

Please see the following code and it comments. It creates a range A1:A3 and it appears inside the collection returned by GetNamedRanges() method

Workbook workbook = new Workbook();

Worksheet worksheet = workbook.Worksheets[0];
Range range = worksheet.Cells.CreateRange("A1:A3");
range.Name = "MyRange";

//Now your range will appear inside this collection
var sheetRanges = worksheet.Workbook.Worksheets.GetNamedRanges();

Console.WriteLine(sheetRanges[0]);

Here is the console output of the above code for your reference.

Aspose.Cells.Range [ MyRange : Sheet1!A1:A3 ]

Note: I am working as Developer Evangelist at Aspose

shakeel
  • 1,717
  • 10
  • 14
  • I did assign a name and it already shows up in GetNamedRanges, but I want it to show up in worksheet.Cells.Ranges – Boris Callens Sep 09 '15 at 12:16
  • Thanks for your clarification. You need to use AddRange() method to add Range inside the Ranges collection. Please check my second answer for sample code. – shakeel Sep 09 '15 at 14:03
0

Please use Worksheet.Cells.AddRange() method to add range inside the Worksheet.Cells.Ranges collection.

Please see the following sample code for your reference.

Workbook workbook = new Workbook();

Worksheet worksheet = workbook.Worksheets[0];

Range range = worksheet.Cells.CreateRange("A1:A3");

worksheet.Cells.AddRange(range);

Console.WriteLine(worksheet.Cells.Ranges[0]);
shakeel
  • 1,717
  • 10
  • 14