PHP 8.2下CodeIgniter3+PHP Spreadsheet导出Excel报错求助
问题分析与解决方案
核心报错原因
你的report_array是关联数组格式,但代码中错误使用了对象属性访问符->取值($value->$value_col),PHP 8.2对这类类型不匹配的错误检测更严格,直接抛出「Trying to get property of non-object」致命错误。
修复步骤
1. 修正数据取值方式
将循环中的对象访问语法替换为数组取值语法:
foreach ($report_array as $key => $value) { $col_count = 1; foreach ($col_array_key as $key_c => $value_col) { // 替换 $value->$value_col 为数组访问方式 $sheet->setCellValue($this->getNameFromNumber($col_count) . $row_count, $value[$value_col]); $col_count++; } $row_count++; }
2. 补充空值处理(可选但推荐)
为避免空字段或未定义键导致的潜在问题,可添加默认值处理:
$cellValue = isset($value[$value_col]) ? $value[$value_col] : ''; $sheet->setCellValue($this->getNameFromNumber($col_count) . $row_count, $cellValue);
3. 确认命名空间引入
确保控制器顶部已引入PHP Spreadsheet的命名空间(若ciSpreadsheet库未自动处理):
use PhpOffice\PhpSpreadsheet\Spreadsheet; use PhpOffice\PhpSpreadsheet\IOFactory;
4. 修正响应头适配XLSX格式
将旧版Excel的Content-Type替换为XLSX对应的标准MIME类型:
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
完整修正后的代码片段
$fileName = 'activityReport.xlsx'; $this->load->library('ciSpreadsheet'); $spreadsheet = new Spreadsheet(); $spreadsheet->getProperties() ->setCreator("CalibOn") ->setLastModifiedBy("CalibOn") ->setTitle("Activity Report") ->setSubject("Activity Report") ->setDescription("Activity Report") ->setKeywords("") ->setCategory("Report"); $spreadsheet->setActiveSheetIndex(0); $col_array = array('Activity Date', 'Activity Time', 'Account Name', 'Activity Type', 'Contacted', 'Outcome', 'Description', 'Activity By', 'Created Date', 'Created Time'); $col_array_key = array('ActivityDate', 'ActivityTime', 'AccountName', 'ActivityType', 'Contacted', 'Outcome', 'Description', 'ActivityBy', 'CreatedDate', 'CreatedTime'); $col_count = 1; $row_count = 1; $sheet = $spreadsheet->getActiveSheet(); foreach ($col_array as $value) { $sheet->setCellValue($this->getNameFromNumber($col_count) . $row_count, $value); $col_count++; } $row_count++; foreach ($report_array as $key => $value) { $col_count = 1; foreach ($col_array_key as $key_c => $value_col) { $cellValue = isset($value[$value_col]) ? $value[$value_col] : ''; $sheet->setCellValue($this->getNameFromNumber($col_count) . $row_count, $cellValue); $col_count++; } $row_count++; } header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'); header('Content-Disposition: attachment;filename="' . $fileName . '"'); header('Cache-Control: max-age=0'); $writer = IOFactory::createWriter($spreadsheet, 'Xlsx'); $writer->save("php://output"); exit;
内容的提问来源于stack exchange,提问作者Pratik Purohit
相关产品推荐
相关产品推荐

