phpexcel导入excel文件报the filename xxx is not recognised as an OLE file错误

错误描述:phpexcel导入excel文件报the filename xxx is not recognised as an OLE file错误。

这个错误其实不是什么大事。只因为今天用微擎框架写项目的时候发现导入Excel文件出错了。所以记录下来,如果有其他人再遇到此类问题,可以参考下面的方法去解决。

微擎phpexcel原始代码:

  1. public function import($excefile)
  2.     {
  3.         global $_W;
  4.         require_once IA_ROOT . '/framework/library/phpexcel/PHPExcel.php';
  5.         require_once IA_ROOT . '/framework/library/phpexcel/PHPExcel/IOFactory.php';
  6.         require_once IA_ROOT . '/framework/library/phpexcel/PHPExcel/Reader/Excel5.php';
  7.         $path = IA_ROOT . '/addons/ewei_shopv2/data/tmp/';
  8.         if (!(is_dir($path)))
  9.         {
  10.             load()->func('file');
  11.             mkdirs($path, '0777');
  12.         }
  13.         $filename = $_FILES[$excefile]['name'];
  14.         $tmpname = $_FILES[$excefile]['tmp_name'];
  15.         if (emptyempty($tmpname))
  16.         {
  17.             message('请选择要上传的Excel文件!', '', 'error');
  18.         }
  19.         $ext = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
  20.         if (($ext != 'xlsx') && ($ext != 'xls'))
  21.         {
  22.             message('请上传 xls 或 xlsx 格式的Excel文件!', '', 'error');
  23.         }
  24.         $file = time() . $_W['uniacid'] . '.' . $ext;
  25.         $uploadfile = $path . $file;
  26.         $uploadfile = iconv("utf-8""gb2312"$uploadfile); //强制转码
  27.         $result = move_uploaded_file($tmpname$uploadfile);
  28.         if (!($result))
  29.         {
  30.             message('上传Excel 文件失败, 请重新上传!', '', 'error');
  31.         }
  32.         $reader = PHPExcel_IOFactory::createReader(($ext == 'xls' ? 'Excel5' : 'Excel2007'));
  33.         $excel = $reader->load($uploadfile);
  34.         $sheet = $excel->getActiveSheet();
  35.         $highestRow = $sheet->getHighestRow();
  36.         $highestColumn = $sheet->getHighestColumn();
  37.         $highestColumnCount = PHPExcel_Cell::columnIndexFromString($highestColumn);
  38.         $values = array();
  39.         $row = 1;
  40.         while ($row <= $highestRow)
  41.         {
  42.             $rowValue = array();
  43.             $col = 0;
  44.             while ($col < $highestColumnCount)
  45.             {
  46.                 $rowValue[] = (string) $sheet->getCellByColumnAndRow($col$row)->getValue();
  47.                 ++$col;
  48.             }
  49.             $values[] = $rowValue;
  50.             ++$row;
  51.         }
  52.         return $values;
  53.     }

对于题目中报的错误经过排查是因为创建的解析器无法解析上传的文件导致的。这行代码就是上面的第32行。

那么解决方法一共有两种:

方法一:先检查下文件类型,然后根据文件类型创建解析器。即把32行代码位置改为:

  1. $readertype = PHPExcel_IOFactory::identify($uploadfile);
  2. $reader = PHPExcel_IOFactory::createReader($readertype);

方法二:直接为上传的文件创建解析器。

  1. $reader = PHPExcel_IOFactory::createReaderForFile($uploadfile);

其实根据文件扩展名创建解析器一般情况下是没有问题的,遇到部分文件可能会出现解析错误。所以大家在开发过程中一定要灵活选择方法。

你想把广告放到这里吗?

发表评论

您必须 登录 才能发表留言!