2016-12-30 60 views
3

我想从PHP中的Excel文件中读取数据,以便我可以处理数据并将其插入到数据库中。
环顾SO,它看起来像PHPExcel是这个任务的首要库。如何使用PHPExcel从Excel文件读取数据?

我去了PHPExcel GitHub页面(https://github.com/PHPOffice/PHPExcel),但我无法弄清楚如何实际使用库。有很多示例文件,我看到的文件都不符合我所寻找的简单用例。
此外,我甚至无法确定我甚至需要下载哪些GitHub页面的文件以及包含文件的文件夹结构。

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

+1

PHPExcel已经从20移动到21世纪。使用composer进行安装,或者做一个git pull(不要试图选择你想要的单个文件),或者至少点击“克隆或下载”按钮并以zip形式下载。 –

+1

[使用PHPExcel将数据插入数据库的示例](http://stackoverflow.com/questions/9695695/how-to-use-phpexcel-to-read-data-and-insert-into-database) –

+0

谢谢为指针,马克。稍微玩了一下之后,我才得以开始工作。我会发布我做的答案。谢谢。 – HartleySan

回答

11

马克贝克非常有助于指导我正确的答案。我不使用作曲家与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>'; 
    } 
相关问题