除非您确定范围始终为 10x10,在这种情况下,只需更改循环条件,您将需要一种检测连续值的方法。
此代码段应该可以帮助您这样做
/// <summary>
/// gets the number of consecutive (without any empty cell) values vertically
/// </summary>
/// <param name="aRow"></param>
/// <param name="aColumn"></param>
/// <returns></returns>
public int GetNumberConsecValues(int aRow, int aColumn)
{
int wCount = 0;
while (this[aRow + wCount, aColumn] != null)
{
wCount++;
}
return wCount;
}
并根据需要使用它将值读入数组/矩阵:
/// <summary>
/// Reads the vertical array from the specified cell
/// </summary>
/// <param name="aRow"></param>
/// <param name="aColumn"></param>
/// <returns></returns>
public int[] ReadArrayInt(int aRow, int aColumn)
{
int wNbValues = this.GetNumberConsecValues(aRow, aColumn);
if (wNbValues == 0)
return null;
int[] wArr = new int[wNbValues];
for (int iRow = 0; iRow < wNbValues; iRow++)
{
wArr[iRow] = Convert.ToInt32(this[aRow + iRow, aColumn]);
}
return wArr;
}
如果您知道范围,那么您可以使用这个其他代码片段
public object[,] ReadRange(int aColFrom, int aColTo, int aRowFrom, int aRowTo)
{
this.BeginUpdate();
try
{
SpreadsheetGear.IRange oRange = m_ViewLock.Workbook.ActiveWorksheet.Cells[aRowFrom, aColFrom, aRowTo, aColTo];
object[,] oValues = new object[aRowTo - aRowFrom + 1, aColTo - aColFrom + 1];
int iRCol = 0;
for (int iCol = aColFrom; iCol <= aColTo; iCol++)
{
int iRRow = 0;
for (int iRow = aRowFrom; iRow <= aRowTo; iRow++)
{
oValues[iRRow, iRCol] = oRange.Cells[iRRow, iRCol].Value;
iRRow++;
}
iRCol++;
}
return oValues;
}
finally
{
this.EndUpdate();
}
}
其中 BeginUpdate 和 EndUpdate 定义为:
/// <summary>
/// Must be called before the grid is being modified
/// We also call it inside every method so that if the user forgets to call it is no big deal
/// For this reason the calls can be nested.
/// So if the user forgets to make the call it is safe
/// and if the user does not forget he/she gets the full speed benefits..
/// </summary>
public void BeginUpdate()
{
if (m_ViewLockCount == 0)
m_ViewLock = new CWorkbookViewLockHelper(this.Workbook);
m_ViewLockCount++;
}
/// <summary>
/// Must be called after the grid has being modified
/// </summary>
public void EndUpdate()
{
m_ViewLockCount--;
if (m_ViewLockCount <= 0)
{
m_ViewLock.Dispose();
m_ViewLock = null;
}
}