简体   繁体   中英

How do iterate over all cells in a named range in Aspose.Cells for .Net?

I'm working with .Net Apose.Cells. I am trying to figure out to iterate over all the cells in a named range.

I retrieve the named range from the workbook:

Range range = AsposeWorkbook.Worksheets.GetRangeByName(rangeName);

I would like to set the value for each cell in the named range to zero (0). How do I do this? What is the best method for iterating over cells in a named range?

Thanks, JB

You can iterate the cells of your range using the Range.GetEnumerator() method. Once you have access to your Cell object, then you can set its value to 0 using Cell.PutValue() method. Please see the following sample code, its comments and example output

//Load your excel file
Workbook workbook = new Workbook("s1.xlsx");

//Access first worksheet
Worksheet ws = workbook.Worksheets[0];

//THis way you can create range on runtime
Range rn = ws.Cells.CreateRange("A1:D6");
rn.Name = "MyRange";

//Access your range as you have been doing before
Range range = workbook.Worksheets.GetRangeByName("MyRange");

//Iterate all the cells in your range, print their names and values
IEnumerator e = range.GetEnumerator();

while (e.MoveNext())
{
    Cell c = (Cell)e.Current;
    Console.WriteLine(c.Name + ": " + c.StringValue);

    //Set value to 0
    c.PutValue(0);
}

Example Console Output

A1: 27
B1: 92
C1: 58
D1: 58
A2: 75
B2: 21
C2: 61
D2: 27
A3: 55
B3: 49
C3: 73
D3: 92
A4: 6
B4: 7
C4: 2
D4: 62
A5: 18
B5: 75
C5: 76
D5: 32
A6: 32
B6: 63
C6: 18
D6: 34

Note: I am working as Developer Evangelist at Aspose

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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