如何在 CodeIgniter 3 中使用 PHPSpreadsheet 从 Excel(.xlsx 和 .xls)文件中读取数据?

How to use PHPSpreadsheet in CodeIgniter 3 to read data from Excel (.xlsx and .xls) file?

最近在我的一个基于 CodeIgniter 的项目中,我需要从 Excel 文件(.xlsx 和 .xls)中读取数据并将这些数据插入 MySQL。不幸的是,我之前没有使用 PHPSpreadsheet(因为我不需要使用 Excel :( ).

到目前为止我所做的是,从 Github 下载 PHPSpreadsheet 并将其解压缩到我的 CodeIgniter[=36= 的根目录] 项目。

CodeIgniter 根目录中的 PHPSpreadsheet。

PHPSpreadsheet 的文件结构。

到目前为止,我已尝试将官方文档示例导入到我的 CI 应用程序中:

<?php
    defined('BASEPATH') OR exit('No direct script access allowed');
    use PhpOffice\PhpSpreadsheet\IOFactory;
    class Welcome extends CI_Controller {
       function __construct() {
           parent::__construct();
       }

       public function index()
       {
           $inputFileType = 'Xlsx';
           $inputFileName = 'test.xlsx';
           $reader = \PhpOffice\PhpSpreadsheet\IOFactory::createReader($inputFileType);
    /**  Load $inputFileName to a Spreadsheet Object  **/
          $spreadsheet = $reader->load($inputFileName);
          print_r( $spreadsheet );
    }
}

但是显示如下错误!!

谁能告诉我如何在 CodeIgniter 中使用 PHPSpreadsheet 从 Excel 文件中读取数据并将它们存储到MySQL数据库?

  • 谢谢

包含 PhpSpreadsheet 的最简单方法是使用 Composer - https://phpspreadsheet.readthedocs.io/en/latest/ 处的文档解释了如何执行此操作。

否则,您将需要一个 PSR4 自动加载器来加载您的 use 语句指定的 class 或自己包含文件。如果您自己包含文件,要阅读 Excel 文件,您需要包含 PhpSpreadsheet/src/PhpSpreadsheet/IOFactory.php