求助:CodeIgniter 3中Excel表格导出与上传的库及用法指导
CodeIgniter 3 结合 PHP 8.2 实现 Excel 上传与导出
推荐使用 PhpSpreadsheet 库,它是 PHPExcel 的官方替代版本,完美支持 PHP 8.2,适配 CodeIgniter 3 环境。
一、Excel 上传并导入到 MySQL
1. 安装 PhpSpreadsheet
- 在项目根目录执行 Composer 命令:
composer require phpoffice/phpspreadsheet
- 修改根目录的
index.php,添加以下代码开启 Composer 自动加载:
require_once APPPATH.'../vendor/autoload.php';
2. 实现上传与导入逻辑
创建控制器 Excel.php,编写上传方法:
<?php defined('BASEPATH') OR exit('No direct script access allowed'); class Excel extends CI_Controller { public function __construct() { parent::__construct(); $this->load->model('Excel_model'); // 提前创建数据模型 } // Excel 上传处理 public function upload() { // 配置上传规则 $config['upload_path'] = './uploads/'; $config['allowed_types'] = 'xls|xlsx'; $config['max_size'] = 10240; // 10MB $this->load->library('upload', $config); if (!$this->upload->do_upload('excel_file')) { // 上传失败,返回错误信息 echo $this->upload->display_errors(); } else { // 上传成功,获取文件信息 $file_data = $this->upload->data(); $file_path = $file_data['full_path']; // 加载 PhpSpreadsheet use PhpOffice\PhpSpreadsheet\IOFactory; $spreadsheet = IOFactory::load($file_path); $worksheet = $spreadsheet->getActiveSheet(); $highest_row = $worksheet->getHighestRow(); // 从第2行开始读取(第1行是表头) for ($row = 2; $row <= $highest_row; $row++) { $data = [ 'name' => $worksheet->getCell('A'.$row)->getValue(), 'email' => $worksheet->getCell('B'.$row)->getValue(), 'phone' => $worksheet->getCell('C'.$row)->getValue() // 根据你的Excel列和数据库字段调整 ]; // 插入数据库 $this->Excel_model->insert_data($data); } echo '数据导入成功!'; // 可选:删除上传的临时文件 unlink($file_path); } } }
3. 数据模型(Excel_model.php)
<?php class Excel_model extends CI_Model { public function insert_data($data) { return $this->db->insert('your_table_name', $data); // 替换为你的表名 } }
二、从 MySQL 导出 Excel
1. 实现导出逻辑
在 Excel.php 控制器中添加导出方法:
public function export() { // 查询MySQL数据 $data = $this->Excel_model->get_all_data(); // 模型中实现查询方法 // 加载PhpSpreadsheet类 use PhpOffice\PhpSpreadsheet\Spreadsheet; use PhpOffice\PhpSpreadsheet\Writer\Xlsx; $spreadsheet = new Spreadsheet(); $sheet = $spreadsheet->getActiveSheet(); // 设置表头 $sheet->setCellValue('A1', '姓名'); $sheet->setCellValue('B1', '邮箱'); $sheet->setCellValue('C1', '电话'); // 填充数据(从第2行开始) $row = 2; foreach ($data as $item) { $sheet->setCellValue('A'.$row, $item['name']); $sheet->setCellValue('B'.$row, $item['email']); $sheet->setCellValue('C'.$row, $item['phone']); $row++; } // 设置响应头,触发下载 header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'); header('Content-Disposition: attachment;filename="导出数据.xlsx"'); header('Cache-Control: max-age=0'); $writer = new Xlsx($spreadsheet); $writer->save('php://output'); exit; }
2. 模型中添加查询方法
public function get_all_data() { return $this->db->get('your_table_name')->result_array(); // 替换为你的表名 }
内容的提问来源于stack exchange,提问作者Anshul Singh
相关产品推荐
相关产品推荐

