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

时间:2010-04-09 18:37:19

标签: c# excel vsto

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

奖励积分如果它也适用于“命名范围”。

4 个答案:

答案 0 :(得分:4)

使用Range对象的Worksheet属性,并将Type.Missing作为第二个参数传递。

例如:

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

这也支持命名范围。

<强> EDITED

答案 1 :(得分:1)

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

换句话说,使用范围对象的Address属性,如下所示:range.Address

答案 2 :(得分:0)

如果您要获取的是单元格的实际内容,请使用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

答案 3 :(得分:0)

string获得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];
    }
}

Range获得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];
    }
}

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

相关问题