Search code examples
phpexcelphpexcelincrement

php increment letter by number


It is pretty simple question but I cannot find best simple solution. I'm trying to render excel where tables will be next to each other in this format:

+---+-------+-------+-------+-------+-------+-------+-------+
|   | B     | C     | D     | E     | F     | G     | H     |
+---+-------+-------+-------+-------+-------+-------+-------+
| 1 |                         TITLE                         |
+---+-------------------------------------------------------+
| 2 | IN    | OUT   | NETTO | TEXT  | TEXT  | TEXT  | TEXT  |
+---+-------+-------+-------+-------+-------+-------+-------+
| 3 | value | value | value | value | value | value | value |
+---+-------+-------+-------+-------+-------+-------+-------+

To render title I begin from cell B1 to cell H1 so my first attempt was this:

$column = 'B'; // default column number
foreach ($data as $tables) {
    $r = 1; // row number
    foreach ($tables as $table) {
        $this->excel->getActiveSheet()->SetCellValue($column . $r . ':' . $column + 6 . $r, $connector_name);
        $r++;
        // then row with header r++
        // then row with values
        $column++;
        // other table starting in cell I1
    }
}

In each table I start in row 1 and I need to move horizontaly so that is why I need to move to others columns by incrementing. The problem is in cell with title where I need cells B1:H1. B1 is simple but then I don't know how to increment column by 6 to get letter H - $column + 6 doesn't work. Have any idea how to do it with simple solution?


Solution

  • functions ord and chr will help you

    echo chr(ord($column)+6); // H
    

    Note this will work till the Letter // Z only..