PHPSpreadsheet - 无法更新现有电子表格但可以写入新电子表格?

PHPSpreadsheet - can't update an existing spreadsheet but can write to new spreadsheet?

所以我正在使用 PHPSpreadsheet 写入现有的电子表格,但由于某种原因我不断收到此错误:

PHP Fatal error:  Uncaught Error: Call to a member function setValue() on null in /home/joe/vendor/phpoffice/phpspreadsheet/samples/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/Worksheet.php:1127
Stack trace:
#0 /home/joe/vendor/phpoffice/phpspreadsheet/samples/server.php(90): PhpOffice\PhpSpreadsheet\Worksheet\Worksheet->setCellValue('b15', '6429093')
#1 {main}
  thrown in /home/joe/vendor/phpoffice/phpspreadsheet/samples/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Worksheet/Worksheet.php on line 1127

我只会在尝试从现有电子表格加载时遇到此错误,而在从新电子表格加载时不会。代码如下:

$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$letters = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','aa','ab','ac','ad','ae','af','ag','ah','ai','aj','ak','al','am','an','ao','ap','aq','ar','as','at','au','av','aw','ax','ay','az','ba','bb','bc','bd','be'];

    $numColumns = count($letters);

    foreach($rows as $row) {

        foreach($row as $key => $value) {

            if(isset($value) && $value != null) {

                $sheet->setCellValue($letters[$key].$i, $value);
            }

            //print_r();
        }

        $i++;
    }

我从中加载的电子表格只包含一堆单元格格式和一些已经包含数据的单元格。如果您能提供任何帮助,那就太好了:-)

字母要大写,不能小写,这个方法是通过ascii码获取char。并将其转换为带有函数 chr 的字符。

ascii code.
chr php function

$letters = range(65, 90) // A-Z ascii code

foreach($rows as $i => $row) {

   foreach($row as $j => $value) {

     if(isset($value) && $value != null) {

        // array start from 0, but spreadsheet line start from 1. then $i+1  
        $sheet->setCellValue( chr($letters[$j]).($i+1) , $value); // A1, $value
     }

     //print_r();
   }
 }