Skip to content

Instantly share code, notes, and snippets.

@technetium
Created January 23, 2018 08:55
Show Gist options
  • Save technetium/2c19431639f89cab7b7d7e1ec423035e to your computer and use it in GitHub Desktop.
Save technetium/2c19431639f89cab7b7d7e1ec423035e to your computer and use it in GitHub Desktop.
<?php
namespace AppBundle\Twig\Extension;
/**
* A TWIG Extension which allows to generate a range of excel columns
* Since excel works with column names instead of numbers a range of names is needed.
*/
class ExcelExtension extends \Twig_Extension
{
public function getFunctions()
{
return [
new \Twig_SimpleFunction('excelColumnNames', [$this, 'excelColumnNames']),
];
}
/**
* @param $start The name of the start column e.g. 'D', optional default is 'A'
* @param null|int|string $length Either the length of the range e.g. 7 or the name of the last column name e.g. 'J'
* @return \Generator
*/
public function excelColumnNames($start, $length=null)
{
if (is_null($length))
{
$length = $start;
$start = 'A';
}
$i = 0;
if (!is_int($length)) { $length++; }
while (
(is_int($length) && $i < $length) ||
(!is_int($length) && $start != $length) // Since in PHP 'AC' < 'D' we cannot use the lesser than operator.
// So no protection against an end column smaller than start.
) {
yield $start;
$i++;
$start++;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment