Algorithm to get the excel-like column name of a number

后端 未结 10 1859
囚心锁ツ
囚心锁ツ 2020-11-30 18:08

I\'m working on a script that generate some Excel documents and I need to convert a number into its column name equivalent. For example:

1 => A
2 => B
         


        
10条回答
  •  青春惊慌失措
    2020-11-30 18:42

    Using PhpSpreadsheet (PHPExcel is deprecated)

    // result = 'A'
    \PhpOffice\PhpSpreadsheet\Cell\Coordinate::stringFromColumnIndex(1);
    

    Note index 0 results in 'Z'

    https://phpspreadsheet.readthedocs.io/en/develop/


    The correct answer (if you use PHPExcel Library) is:

    // result = 'A'
    $columnLetter = PHPExcel_Cell::stringFromColumnIndex(0); // ZERO-based! 
    

    and backwards:

    // result = 1
    $colIndex = PHPExcel_Cell::columnIndexFromString('A');
    

提交回复
热议问题