所以我正在使用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++;
}
我要从中加载的电子表格仅包含一堆单元格格式以及一些已经有数据的单元格。您可以提供的任何帮助都将是非常棒的:-)
答案 0 :(得分:0)
字母应该是大写,而不是小写,此方法是通过ascii代码获取char。并将其转换为带有功能chr
的字符。
$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();
}
}