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

问题描述 投票:0回答:2

我想从 PHP 中的 Excel 文件读取数据,以便我可以处理数据并将其插入数据库。
环顾四周,PHPExcel 似乎是完成此任务的首要库。

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

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

php excel phpexcel phpexcelreader phpexcel-1.8.0
2个回答
20
投票

马克·贝克(Mark Baker)在指导我找到正确答案方面非常有帮助。我不将 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>';
  }

0
投票

您可以使用开源 TurboDepot 库轻松做到这一点:

首先获取最新的 phar 文件并将它们作为依赖项集成到您的项目中。初始化 XlsxObject 类并输入 xlsx 文件的二进制数据:

<?php

require 'path/to/your/dependencies/folder/turbocommons-php-X.X.X.phar';
require 'path/to/your/dependencies/folder/turbodepot-php-X.X.X.phar';

use org\turbodepot\src\main\php\model\XlsxObject;

// Load the xlsx file
$xlsx = new XlsxObject(file_get_contents('path/to/your/file.xlsx'));

$numSheets = $xlsx->countSheets(); // Retrieve the total number of sheets
$cellValue = $xlsx->getCell($rowIndex, $colIndex); // Obtain the value at specified indices
$totalCells = $xlsx->countCells();
$totalRows = $xlsx->countRows();
$totalColumns = $xlsx->countColumns();

欲了解更多见解,请参阅:

https://turboframework.org/en/blog/2024-04-29/load-and-operate-with-xlsx-files-in-php

© www.soinside.com 2019 - 2024. All rights reserved.