findAndReplace method

int findAndReplace(
  1. dynamic source,
  2. dynamic target, {
  3. int first = -1,
  4. int startingRow = -1,
  5. int endingRow = -1,
  6. int startingColumn = -1,
  7. int endingColumn = -1,
})

Returns the count of replaced source with target

source is dynamic which allows you to pass your custom RegExp providing more control over it.

optional argument first is used to replace the number of first earlier occurrences

If first is set to 3 then it will replace only first 3 occurrences of the source with target.

  excel.findAndReplace('MySheetName', 'sad', 'happy', first: 3);

  or

  var mySheet = excel['mySheetName'];
  mySheet.findAndReplace('sad', 'happy', first: 3);

In the above example it will replace all the occurences of sad with happy in the cells

Other options are used to narrow down the starting and ending ranges of cells.

Implementation

int findAndReplace(dynamic source, dynamic target,
    {int first = -1,
    int startingRow = -1,
    int endingRow = -1,
    int startingColumn = -1,
    int endingColumn = -1}) {
  int replaceCount = 0,
      _startingRow = 0,
      _endingRow = -1,
      _startingColumn = 0,
      _endingColumn = -1;

  if (startingRow != -1 && endingRow != -1) {
    if (startingRow > endingRow) {
      _endingRow = startingRow;
      _startingRow = endingRow;
    } else {
      _endingRow = endingRow;
      _startingRow = startingRow;
    }
  }

  if (startingColumn != -1 && endingColumn != -1) {
    if (startingColumn > endingColumn) {
      _endingColumn = startingColumn;
      _startingColumn = endingColumn;
    } else {
      _endingColumn = endingColumn;
      _startingColumn = startingColumn;
    }
  }

  int rowsLength = maxRows, columnLength = maxCols;
  RegExp sourceRegx;
  if (source.runtimeType == RegExp) {
    sourceRegx = source;
  } else {
    sourceRegx = RegExp(source.toString());
  }

  for (int i = _startingRow; i < rowsLength; i++) {
    if (_endingRow != -1 && i > _endingRow) {
      break;
    }
    for (int j = _startingColumn; j < columnLength; j++) {
      if (_endingColumn != -1 && j > _endingColumn) {
        break;
      }
      if (_sheetData.isNotEmpty &&
          _sheetData[i] != null &&
          _sheetData[i]![j] != null &&
          sourceRegx.hasMatch(_sheetData[i]![j]!.value.toString()) &&
          (first == -1 || first != replaceCount)) {
        _sheetData[i]![j]!
            .value
            .toString()
            .replaceAll(sourceRegx, target.toString());

        replaceCount += 1;
      }
    }
  }

  return replaceCount;
}