如何使用PHPExcel从Excel文件中读取数据?

时间:2016-12-30 15:37:31

标签: php excel phpexcel phpexcelreader phpexcel-1.8.0

我想从PHP中的Excel文件中读取数据,以便我可以处理数据并将其插入到数据库中 环顾四周,看起来PHPExcel是这项任务的首选库。

我访问了PHPExcel GitHub页面(https://github.com/PHPOffice/PHPExcel),但我无法弄清楚如何实际使用该库。有大量的示例文件,我看到的所有文件似乎都与我正在寻找的简单用例相匹配。
此外,我甚至无法弄清楚GitHub页面中哪些文件甚至需要下载以及包含文件的文件夹结构需要什么。

因此,考虑到上面链接的GitHub页面的构建方式(对于v1.8),我需要下载哪些文件以及允许我提供Excel文件路径的简单代码示例从文件中读取数据?

1 个答案:

答案 0 :(得分:13)

Mark Ba​​ker在指导我找到正确答案方面非常有帮助。我不使用Composer with PHP(我应该学习),但鉴于此,为了实现这一点,我去了PHPExcel的GitHub页面(https://github.com/PHPOffice/PHPExcel),点击绿色克隆和下载按钮,然后下载ZIP 链接。

解压缩文件后,我找到了一个名为PHPExcel-1.8的文件夹。我将该文件夹移动到与我想要阅读的Excel文件相同的文件夹(在我的代码test.xlsx下面)和包含以下代码的PHP文件。

让它工作的关键是输入IOFactory.php文件的正确路径。对某些人来说这似乎很简单,但这让我感到很沮丧。

鉴于上述内容和Mark Ba​​ker的评论,以下代码对我来说非常有效(请注意评论部分):

<?php

  //Had to change this path to point to IOFactory.php.
  //Do not change the contents of the PHPExcel-1.8 folder at all.
  include('PHPExcel-1.8/Classes/PHPExcel/IOFactory.php');

  //Use whatever path to an Excel file you need.
  $inputFileName = 'test.xlsx';

  try {
    $inputFileType = PHPExcel_IOFactory::identify($inputFileName);
    $objReader = PHPExcel_IOFactory::createReader($inputFileType);
    $objPHPExcel = $objReader->load($inputFileName);
  } catch (Exception $e) {
    die('Error loading file "' . pathinfo($inputFileName, PATHINFO_BASENAME) . '": ' . 
        $e->getMessage());
  }

  $sheet = $objPHPExcel->getSheet(0);
  $highestRow = $sheet->getHighestRow();
  $highestColumn = $sheet->getHighestColumn();

  for ($row = 1; $row <= $highestRow; $row++) { 
    $rowData = $sheet->rangeToArray('A' . $row . ':' . $highestColumn . $row, 
                                    null, true, false);

    //Prints out data in each row.
    //Replace this with whatever you want to do with the data.
    echo '<pre>';
      print_r($rowData);
    echo '</pre>';
  }