如何为Xlsx文件生成pCoordinates

时间:2020-04-14 15:03:10

标签: php file spreadsheet axlsx generate

我要为此生成坐标

 $sheet->setCellValue($pCoordinate, $pValue);

$ pCoodrinates是字母,然后是数字,例如A1,B1,C1,例如第一行,然后下一行是A2,B2,C2,下一行是3

这是我现在拥有的代码

class SpreadSheetHelper
{
    private static $alphabet = 'ABCDEFGHIJKLMNOPQRSTUYVWXYZ';

    public static function createSpreadSheet($data = []) {
        $spreadsheet = new Spreadsheet();
        $sheet       = $spreadsheet->getActiveSheet();
        foreach ($data as $rowIndex => $row) {
            foreach ($row as $columnIndex => $columnValue) {
                $pCoordinate = self::getAlphabetCoordinate($rowIndex, $columnIndex);
                $pValue = $columnValue;
                $sheet->setCellValue($pCoordinate, $pValue);
            }
        }

        return $spreadsheet;
    }


    private static function getAlphabetCoordinate($rowIndex, $columnIndex) {
        $letter = strtoupper(substr(self::$alphabet, $columnIndex, 1));
        $number = $rowIndex + 1;
        return "$letter$number";
    }
}

如您所见,$ alphabet是硬编码且受限制的,它到达的最后一个字母应以AA,AB,AC,AD,AE,AF开头,这就是我想要生成的。知道怎么做吗?

1 个答案:

答案 0 :(得分:1)

您可以利用ASCII表:

<?php
//Number of rows and columns
$rows = 3;
$cols = 40;

$pcoords = array();
for($current_row=1;$current_row<$rows+1;$current_row++) {
    $alpha_index = 65;
    $alpha_pref_index = 65;
    $alpha_count = 0;
    $pref_letter = '';

    for($current_col=0;$current_col<$cols;$current_col++) {
        $col_letter = chr($alpha_index);
        $pcoords[] = $pref_letter . $col_letter. $current_row;
        $alpha_count++;
        if ($alpha_count == 26) {
            $alpha_count = 0;
            $alpha_index = 65;
            $pref_letter = chr($alpha_pref_index);     
            $alpha_pref_index++;               
        }
        else {
            $alpha_index++;            
        }        
    }    
}

echo '<pre>';
print_r($pcoords);
echo '</pre>';
相关问题