使用Phpspreadsheet读取Excel时遇“File does not exist”错误求助
解决PhpSpreadsheet提示“File does not exist”的问题
嘿,我一眼就揪出问题所在了——你给PhpSpreadsheet传的是HTTP网址,但这个库根本不认网络路径,它只接受服务器本地的文件系统路径!
问题根源
你用base_url()生成的路径是这种格式:
http://localhost:8000/userfiles/product/excelfiles/452260670768Untitledspreadsheet.xlsx
这是供浏览器访问的网页地址,而PhpSpreadsheet需要的是服务器硬盘上的真实路径(比如/var/www/html/userfiles/product/excelfiles/xxx.xlsx,或者项目根目录下的相对路径)。
修复步骤
从代码里的$this->input->post能看出来你用的是CodeIgniter框架,直接用框架提供的FCPATH常量就能拿到项目根目录的绝对路径,替换掉原来的base_url()就行:
$product_serial = $this->input->post('product_serial'); // 用FCPATH生成本地文件路径,替代base_url() $excelFilePath = FCPATH . 'userfiles/product/excelfiles/' . $product_serial; try { $reader = \PhpOffice\PhpSpreadsheet\IOFactory::createReaderForFile($excelFilePath); $spreadSheet = $reader->load($excelFilePath); $dataAsAssocArray = $spreadSheet->getActiveSheet()->toArray(); } catch (\Exception $exception){ echo $exception->getMessage(); }
额外要检查的点
- 验证路径是否正确:可以临时加一行
echo $excelFilePath;,输出的应该是类似/your/project/path/userfiles/product/excelfiles/452260670768Untitledspreadsheet.xlsx的本地路径 - 检查文件权限:确保服务器的web运行用户(比如
www-data、apache)有这个文件的读取权限,不然就算路径对了也会报错
内容的提问来源于stack exchange,提问作者Nauman Bashir
相关产品推荐
相关产品推荐

