Excel.Range在C#中的string转换

使用.NET的Office互操作库,有没有人知道在string之间来回转换的最佳方式(例如“A57”,“$ L $ 2:$ M:$ 3”)和相应的Excel.Rangetypes的对象?

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

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

例如:

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

这也支持命名范围。

EDITED

正如SLaks所说,你可以通过工作表的Range属性(如worksheet.Range["A3:C30"]从string地址中获得一个范围对象。 .NET 4.0中可以省略第二个参数。 .get_Range()等同于.Range[]

range.Address一种方式,使用Range对象的Address属性如下: range.Address

如果您试图获得单元格的实际内容,请使用Value2属性。 下面是一些检查单元值types的代码,并相应地做了不同的事情。

 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

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

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

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