5

I want to read data from an Excel file in PHP so that I can process the data and insert it into a DB.
Looking around SO, it looks like PHPExcel is the premier library for this task.

I went to the PHPExcel GitHub page (https://github.com/PHPOffice/PHPExcel), but I cannot figure out how to actually use the library. There are a ton of example files and none of the ones I looked at seem to match the simple use case I'm looking for.
Furthermore, I cannot even figure out which files from the GitHub page I even need to download and what the folder structure for the include file(s) needs to be.

As such, given the way the GitHub page linked above is structured now (for v1.8), what files do I need to download and what is a simple code example that allows me to provide a path to an Excel file and read the data from the file?

4

1 回答 1

20

马克贝克在指导我找到正确答案方面非常有帮助。我不将 Composer 与 PHP 一起使用(我可能应该学习),但鉴于此,为了让它工作,我去了 PHPExcel 的 GitHub 页面(https://github.com/PHPOffice/PHPExcel),点击绿色克隆和下载按钮,然后是下载 ZIP链接。

解压缩文件后,我得到一个名为PHPExcel-1.8. 我将该文件夹移动到与我想要读取的 Excel 文件(在下面的代码中test.xlsx)和具有下面代码的 PHP 文件相同的文件夹中。

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

鉴于上述和马克贝克的评论,以下代码对我来说非常有效(注意注释部分):

<?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>';
  }
于 2016-12-30T17:06:24.547 回答