(object )range.get_Value(XL.XlRangeValueDataType.xlRangeValueDefault)导致转换错误
错误:
Cannot convert type 'string' to 'object[*,*]'
这是我得到的错误。 有人能给我一些指针,以便我可以避免它? 谢谢。
注意:
有趣的是, (object[,])range.get_Value(XL.XlRangeValueDataType.xlRangeValueDefault)
当range.Count == 1
时只会产生这个bug。 当count等于或大于2时,它工作正常。
示例代码:
object[,] arrValue; //global variable private string[] createFormulaCollection() { ArrayList s = new ArrayList(); try { //look at the currently active excel sheet //iterate through cells (not Null) and find the one contains IES(...) //save it into the arraylist //use dictionary to save position and value (position as key) workbook = Globals.ThisAddIn.Application.ActiveWorkbook; worksheet = Globals.ThisAddIn.Application.ActiveSheet; range = worksheet.UsedRange; MessageBox.Show(range.Count.ToString()); if (range.Count > 1) { //need to make sure there are at least 2 "ies" cells before converting to object[,] arrValue = (object[,])range.get_Value(XL.XlRangeValueDataType.xlRangeValueDefault); } else { arrValue[1,1] = range.get_Value(XL.XlRangeValueDataType.xlRangeValueDefault); //my try here. seems still got problem though. } catch (Exception ex) { } return (string[])s.ToArray(typeof(string)); }
发现:
range.get_Value(XL.XlRangeValueDataType.xlRangeValueDefault);
当range.Count == 1时将返回一个string,这意味着它不能被转换为object [,] type。
它可以,但是,当range.Count> 1。
我的解决方法:
只要分开处理。 所以在我的情况下,我必须首先计数范围对象的数量,并相应地处理它们。
if(range.Count > 1) { //code... } else { string singleStrValue = range.get_Value(XL.XlRangeValueDataType.xlRangeValueDefault); int iRow, iCol; iRow = range.Row; iCol = range.Column; if (!string.IsNullOrEmpty(singleStrValue)) { //code... } }
它是否工作
(object[,])range.get_Value(System.Reflection.Missing.Value);