Laravel Excel导出多图片报错:Call to a member function setWorksheet() on array
解决Laravel Excel多张图片导出时"Call to a member function setWorksheet() on array"错误
错误原因
Maatwebsite/Laravel Excel的drawings()方法要求返回一维的Drawing对象数组,但你的代码返回了包含三个子数组的二维数组。框架在遍历返回值时,会把每个子数组当成Drawing对象调用setWorksheet()方法,从而触发该错误。
修正方案
将所有创建的Drawing对象合并到一个一维数组中返回,而非嵌套数组。
修正后的完整代码
public function drawings() { $Pengaduan = Pengaduan::select( 'pengaduanTiket', 'nama_lengkap', 'no_hp', 'no_kk', 'no_ktp', 'alamat_sesuai_ktp', 'nama_pengaduan', 'jenis_pengaduan', 'isi_pengaduan', 'status', 'keterangan', 'dokumen_pendukung', 'dokumentasi', 'lampiran', )->whereBetween('created_at', [$this->requestawal, $this->requestakhir])->get(); $images = []; $rowNum = 2; foreach ($Pengaduan as $row) { // 处理 dokumen_pendukung 图片 $file1 = new Drawing(); if (empty($row->dokumen_pendukung)) { $file1->setPath(public_path('/assets/images/default.jpg')); } else { $file1->setPath(public_path('/assets/uploads/images/pengaduan/') . $row->dokumen_pendukung); } $file1->setHeight(20); $file1->setCoordinates('L' . $rowNum); $images[] = $file1; // 处理 dokumentasi 图片 $file2 = new Drawing(); if (empty($row->dokumentasi)) { $file2->setPath(public_path('/assets/images/default.jpg')); } else { $file2->setPath(public_path('/assets/uploads/images/pengaduan/') . $row->dokumentasi); } $file2->setHeight(20); $file2->setCoordinates('M' . $rowNum); $images[] = $file2; // 处理 lampiran 图片 $file3 = new Drawing(); if (empty($row->lampiran)) { $file3->setPath(public_path('/assets/images/default.jpg')); } else { $file3->setPath(public_path('/assets/uploads/images/pengaduan/') . $row->lampiran); } $file3->setHeight(20); $file3->setCoordinates('N' . $rowNum); $images[] = $file3; $rowNum++; } return $images; }
额外优化点
- 原代码中的
setheight修正为规范驼峰命名setHeight(PHP方法名不区分大小写,但遵循规范可避免潜在问题) - 用
empty()替代== null || == ""的判断,代码更简洁且覆盖更多空值场景
内容的提问来源于stack exchange,提问作者Faizal Anwar
相关产品推荐
相关产品推荐

