You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在CodeIgniter3中配置PhpSpreadsheet自动加载并迁移至third_party

在CodeIgniter 3中配置PhpSpreadsheet到third_party并实现自动加载

步骤1:迁移PhpSpreadsheet至third_party目录

  • 下载PhpSpreadsheet完整包,或在application/third_party目录下执行composer require phpoffice/phpspreadsheet,生成包含依赖的文件结构
  • 将PhpSpreadsheet相关文件(含vendor目录)统一放到application/third_party/phpspreadsheet路径下

步骤2:修正自定义Library文件

在application/libraries目录下创建Phpspreadsheet.php,替换为以下代码:

<?php
if (!defined('BASEPATH')) exit('No direct script access allowed');

// 指向third_party目录下的autoload文件
require APPPATH . 'third_party/phpspreadsheet/vendor/autoload.php';

use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;

class Phpspreadsheet extends Spreadsheet
{
    public function __construct()
    {
        parent::__construct();
    }
}

原代码路径错误:__DIR__指向library目录,该目录下无vendor文件夹,需改用APPPATH常量定位third_party下的依赖文件

步骤3:配置自动加载

打开application/config/autoload.php,在$autoload['libraries']数组中添加phpspreadsheet:

$autoload['libraries'] = array('phpspreadsheet', ...);

步骤4:控制器使用示例

<?php
class Test_Excel extends CI_Controller {
    public function export()
    {
        // 调用自动加载的类
        $this->phpspreadsheet->setActiveSheetIndex(0);
        $this->phpspreadsheet->getActiveSheet()->setCellValue('A1', '测试内容');
        
        $writer = new Xlsx($this->phpspreadsheet);
        // 设置响应头实现下载
        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        header('Content-Disposition: attachment;filename="export.xlsx"');
        header('Cache-Control: max-age=0');
        
        $writer->save('php://output');
        exit;
    }
}

故障排查

若仍提示“无法加载请求的类”,检查以下几点:

  • application/third_party/phpspreadsheet/vendor/autoload.php文件是否存在
  • Library文件名与类名是否严格一致(Phpspreadsheet.php对应class Phpspreadsheet)
  • 路径引用是否使用APPPATH常量,避免相对路径错误

内容的提问来源于stack exchange,提问作者mohamed elghamry

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.23 20:42:03