Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Excel.Range to String conversion in C#

Tags:

c#

excel

vsto

Using .NET's Office interop libraries, does anybody know the best way to convert back and forth between strings (eg "A57", "$L$2:$M:$3") and corresponding objects of type Excel.Range?

Bonus points if it also works with "named ranges".

like image 214
mcoolbeth Avatar asked Apr 09 '10 18:04

mcoolbeth


3 Answers

Use the Range property of a Worksheet object, and pass Type.Missing as the second parameter.

For example:

Range range = sheet.get_Range("$L$2:$M:$3", Type.Missing);

This also supports named ranges.

like image 129
SLaks Avatar answered Oct 29 '22 01:10

SLaks


To get a string from a Range:

/// <summary>
/// Extensions to the Range class.
/// </summary>
public static class RangeExtensions
{
    /// <summary>
    /// Returns the range as a string indicating its address.
    /// </summary>
    /// <param name="range">The range to convert to a string.</param>
    /// <returns>A string indicating the range's address.</returns>
    public static string ToAddressString(this Range range)
    {
        return range.Address[true, true, XlReferenceStyle.xlA1, false, null];
    }
}

To get a Range from a string:

public class ExcelUtil
{
    /// <summary>
    /// Converts the given address string on the given sheet to a Range object.
    /// </summary>
    /// <param name="sheet">The worksheet.</param>
    /// <param name="addressString">The address string to convert.</param>
    /// <returns>The range.</returns>
    public static Range RangeFromAddresssString(Worksheet sheet, string addressString)
    {
        return sheet.Range[addressString];
    }
}

The second method might be a little gratuitous, but I prefer being crystal clear in my method names.

like image 20
MgSam Avatar answered Oct 29 '22 02:10

MgSam


As SLaks said, you can get a range object from a string address with the worksheet's Range property like worksheet.Range["A3:C30"]. The second argument can be omitted in .NET 4.0. .get_Range() is equivalent to .Range[].

To go the other way, use the range objects's Address property like this: range.Address.

like image 32
will-mvn Avatar answered Oct 29 '22 02:10

will-mvn