C# C中Excel.Range到字符串的转换#

C# C中Excel.Range到字符串的转换#,c#,excel,vsto,C#,Excel,Vsto,使用.NET的Office interop库,有人知道在字符串(例如“A57”、“L$2:$M:$3”)和Excel.Range类型的相应对象之间来回转换的最佳方法吗 如果它还与“命名范围”一起使用,则可获得额外积分。使用工作表对象的范围属性,并将类型.缺失作为第二个参数传递 例如: Range range = sheet.get_Range("$L$2:$M:$3", Type.Missing); 这也支持命名范围。如果您试图获取的是单元格的实际内容,请使用Value2属

使用.NET的Office interop库,有人知道在字符串(例如“A57”、“L$2:$M:$3”)和Excel.Range类型的相应对象之间来回转换的最佳方法吗


如果它还与“命名范围”一起使用,则可获得额外积分。

使用
工作表
对象的
范围
属性,并将
类型.缺失
作为第二个参数传递

例如:

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

这也支持命名范围。

如果您试图获取的是单元格的实际内容,请使用Value2属性。下面是一些检查单元格值类型并相应地执行不同操作的代码

Excel.Range cell = (Excel.Range)sheet.UsedRange[row, col];
if (cell.Value2 != null)
{
    switch (Type.GetTypeCode(cell.Value2.GetType()))
    {
        case TypeCode.String:
            string formula = cell.Value2;
            break;
        case TypeCode.Double:
            double amt = (Double)cell.Value2;
            break;
    }
}

cell.Value2 = amt + someotheramt;

HTH

正如SLaks所说,您可以使用工作表的
range
属性,如
worksheet.range[“A3:C30”]
从字符串地址获取范围对象。在.NET4.0中可以省略第二个参数
.get_Range()
相当于
.Range[]


另一种方法是,使用范围对象的
Address
属性,如下所示:
range.Address
范围中获取
字符串

/// <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];
    }
}

第二种方法可能有点无缘无故,但我更喜欢在方法名称中清晰明了。

不太清楚您在这里的意思。。。“A57”、“$L$2:$M$3”字符串是否包含要解析为Excel.Range的单元格引用信息,还是指其他内容?这就是我想要的,尽管我对反向操作(从范围到字符串)感兴趣同样。将范围的
名称
属性强制转换为
名称
对象,然后查看属性。您能想出任何原因使范围不出现在Visual Studio工作表的可见属性中吗?如果我自己键入“范围”,它将不会生成。我看到了get_Range,但参数/行为没有很好的文档记录。在c#中,似乎必须使用Range.get_Address()并提供如下所述的参数:
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];
    }
}