public static void Search(ExcelFile xls, TXlsCellRange Range, TCellAddress Start, bool ByRows, TSearchOrReplace Action) { int StartRow = 1; int EndRow = 0; int StartCol = 1; int EndCol = 0; if (Range != null) { StartRow = Range.Top; EndRow = Range.Bottom; StartCol = Range.Left; EndCol = Range.Right; } else { EndRow = xls.RowCount; EndCol = xls.ColCount; } int FirstStartCol = StartCol; int FirstStartRow = StartRow; if (Start != null) { FirstStartRow = Start.Row; if (ByRows) { FirstStartRow++; } FirstStartCol = Start.Col; if (!ByRows) { FirstStartCol++; } if (FirstStartRow > EndRow) { FirstStartRow = StartRow; FirstStartCol++; } if (FirstStartCol > EndCol) { FirstStartCol = StartCol; FirstStartRow++; } } if (ByRows) { SearchByRows(xls, FirstStartRow, StartRow, EndRow, FirstStartCol, EndCol, Action); } else { SearchByCols(xls, FirstStartRow, EndRow, FirstStartCol, StartCol, EndCol, Action); } }
private static void SearchByRows(ExcelFile xls, int FirstStartRow, int StartRow, int EndRow, int StartCol, int EndCol, TSearchOrReplace Action) { int RealEndRow = Math.Min(xls.RowCount, EndRow); int RealEndCol = 0; //we won't use xls.ColCount as it would have to loop over all rows. We can do this here anyway. for (int col = StartCol; col <= EndCol; col++) { int sr; if (col == StartCol) { sr = FirstStartRow; } else { sr = StartRow; } if (col > StartCol + 1 && col > RealEndCol) { break; } for (int row = sr; row <= RealEndRow; row++) { if (col <= StartCol + 1) //We might start searching in the middle of a range. So we need to have at least 2 columns checked to be sure all rows have been inspected for max col. { int ccInRow = xls.ColFromIndex(row, xls.ColCountInRow(row)); if (ccInRow > RealEndCol) { RealEndCol = ccInRow; } } object OldVal = xls.GetCellValue(row, col); if (Action.Go(xls, OldVal, row, col)) { return; } } } Action.Clear(); }
private static void SearchByCols(ExcelFile xls, int StartRow, int EndRow, int FirstStartCol, int StartCol, int EndCol, TSearchOrReplace Action) { int RealEndRow = Math.Min(xls.RowCount, EndRow); for (int row = StartRow; row <= RealEndRow; row++) { int cIndex = row == StartRow?xls.ColToIndex(StartRow, FirstStartCol) : xls.ColToIndex(StartRow, StartCol); int ColsInRow = xls.ColCountInRow(row); while (cIndex <= ColsInRow) { int XF = -1; int col = xls.ColFromIndex(row, cIndex); if (col < StartCol) { cIndex++; continue; } if (col > EndCol) { break; } object OldVal = xls.GetCellValueIndexed(row, cIndex, ref XF); if (Action.Go(xls, OldVal, row, col)) { return; } cIndex++; } } Action.Clear(); }