【问题标题】:PHPExcel unable to read filePHPExcel无法读取文件
【发布时间】:2026-02-15 14:00:02
【问题描述】:

我正在使用 CakePHP 3.2 和 PHPExcel 库将数据从 Excel 工作表导入数据库。

我的图书馆在

/vendor/PHPExcel/Classes/PHPExcel.php
/vendor/PHPExcel/Classes/PHPExcel/IOFactory.php

控制器中的动作是

public function bulkUpload()
{
   $inputFileName = $this->request->data('excel_data');
   //debug($inputFileName['name']);
   if ($inputFileName != '') {
     $inputFileType = \PHPExcel_IOFactory::identify($inputFileName);
     $objReader = \PHPExcel_IOFactory::createReader($inputFileType);

     $objReader->setReadDataOnly(true);
     $objPHPExcel = $objReader->load($inputFileName);
     $objWorksheet = $objPHPExcel->setActiveSheetIndex(0);
     $highestRow = $objWorksheet->getHighestRow();

     for ($row = 2; $row <= $highestRow; ++$row) {
        $this->data['Program']['cycle_month'] = $objWorksheet->getCellByColumnAndRow(1, $row)->getValue();
        $this->data['Program']['cycle_year'] = $objWorksheet->getCellByColumnAndRow(2, $row)->getValue();
        $this->data['Program']['media_partnum'] = $objWorksheet->getCellByColumnAndRow(3, $row)->getValue();

        $resultArray[$row-2] = $this->data['Program'];
     }

      debug($resultArray);
  }
}

但这会产生错误

pathinfo() expects parameter 1 to be string, 
array given [ROOT/vendor/PHPExcel/Classes/PHPExcel/IOFactory.php, line 225]

file_exists() expects parameter 1 to be a valid path, 
array given [ROOT/vendor/PHPExcel/Classes/PHPExcel/Reader/Excel2007.php, line 72]

debug($inputFileName); 它给出了

[
    'name' => 'testing.xlsx',
    'type' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
    'tmp_name' => '/tmp/phpvDWDxG',
    'error' => (int) 0,
    'size' => (int) 5247
]

$inputFileName; 替换为$inputFileName['name']

$inputFileType = \PHPExcel_IOFactory::identify($inputFileName);

删除以上两个错误,但给出错误为

 Could not open testing.xlsx for reading! File does not exist. 

这里,testing.xlsx 是我从表单中选择的文件

【问题讨论】:

  • 那是因为你已经上传了文件,但还没有使用move_uploaded_file()所以它仍然只是一个临时文件;你应该使用$inputFileName['tmp_name']
  • 我也使用了tmp_name,但仍然是同样的错误。没试过move_uploaded_file()。但它与在服务器上保存文件有什么关系。不能直接做吗?
  • 您对“仍然相同的错误”是什么意思,您对 Mark 的评论究竟做了什么尝试?
  • @arilia @mark 说“你应该使用 $inputFileName['tmp_name]”。我已经尝试过这个错误为expects parameter 1 to be string

标签: cakephp phpexcel cakephp-3.2 phpexcelreader


【解决方案1】:
You need to add file like below:

require_once(ROOT. DS .'vendor'.DS.'PHPExcel/Classes/PHPExcel.php');
require_once(ROOT . DS . 'vendor' . DS.'PHPExcel/Classes/PHPExcel/IOFactory.php');

y0ou also need to add a namespace like below

use PHPExcel;
use IOFactory;

Now you can access excel class library and easily read and write

我在我的项目中使用它。

你可以试试。

谢谢:)

【讨论】: