I have some operation that requires to iterate through 3000 excel cell. Problem is that this my code seems pretty bad on performances. I done a little investigation with Stopwatch class to see where do I lose time. My operation lasts for 24 seconds, and just one line of code there consumes 17 seconds. I’m using this code is my class return cell name from cell reference.
public string GetCellName(Range cell)
{
string name = "";
try
{
name = cell.Name.Name;
}
catch { }
return name;
}
It seems really odd to me that this simple code consumes this much time. There are some other parts that should taken longer, for example little for loop with 6-8 elements.
I tried to write this method this way:
public string GetCellName(Range cell)
{
if (cell.Name == null) return "";
else if (cell.Name.Name == null) return "";
else return cell.Name.Name;
}
But than it throws an exception. Do you have any suggestion on how to retrieve Name of excel cell efficiently?
I found that most efficient way is to minimize communication between COM and .NET API. The way to do that is to use
which returns XML format with all the information. Also is possible to use
for populating range with some values.
So you’ll have only one call to COM for getting all values no matter how big your range is, instead calling it once or more for every cell in range. This way you can also format styles to particular cells/range parts, set name for cells/range parts and all the rest.