PHPOffice / PhpSpreadsheet

A pure PHP library for reading and writing spreadsheet files
https://phpspreadsheet.readthedocs.io
MIT License
13.16k stars 3.37k forks source link

add custome sheet fonctions #4048

Open timouchee opened 2 months ago

timouchee commented 2 months ago

i i try to import a new usable function on the sheet a custome function . did some function like "addcustomefunction()" existe already in this current project ??

if not can i have a explaination of how to proffesionaly update the code in order to import in the code my custom function ?

thanks

infojunkie commented 1 month ago

I don't know about "professionally", but I made a one-character modification in the source code to allow adding custom functions: https://github.com/infojunkie/PhpSpreadsheet/commit/69ed95861ad72c4c89a5c6ee7965d1a1fedd2e7c

By returning a reference to the list of functions, you can add a custom function or override an existing one in your own code, like this:

$calculation = $spreadsheet->getCalculationEngine();
$functions = &get_class($calculation)::getFunctions();
$functions['CHOOSECOLS'] = [
  'category' => Category::CATEGORY_MATH_AND_TRIG,
  'functionCall' => [Custom::class, 'choosecols'],
  'argumentCount' => '2+',
];

class Custom
{
  /**
   * CHOOSECOLS.
   *
   * Returns the specified columns from an array.
   *
   * @param mixed $cells The cells being searched
   * @param int $cols List of numeric column indexes to extract
   *
   * @return array|string The resulting array, or a string containing an error
   */
  public static function choosecols(mixed $cells, int ...$cols): array|string
  {
    $columns = RowColumnInformation::COLUMNS($cells);
    if (is_string($columns)) {
      return $columns;
    }
    $result = [];
    foreach ($cols as $col) {
      if (!$col || abs($col) > $columns) {
        return ExcelError::VALUE();
      }
      $result[] = array_column($cells, $col > 0 ? $col-1 : $columns-$col);
    }
    return Matrix::transpose($result);
  }
}