使用.NET的Office互操作库,有人知道在字符串(例如“A57”,“$L$2:$M:$3”)和相应类型为Excel.Range的对象之间来回转换的最佳方法吗?
如果还可以使用“命名范围”,则加分。
使用Worksheet
对象的Range
属性,并将Type.Missing
作为第二个参数传递。
例如:
Range range = sheet.get_Range("$L$2:$M:$3", Type.Missing);
这也支持命名区域。
Range
获取一个string
的方法是:/// <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
的方法是: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];
}
}
正如SLaks所说,您可以使用工作表的Range
属性从字符串地址获取范围对象,例如worksheet.Range["A3:C30"]
。在.NET 4.0中,第二个参数可以省略。.get_Range()
等同于.Range[]
。
要反过来操作,请使用范围对象的Address
属性,例如:range.Address
。
如果您想获取单元格的实际内容,请使用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