如何使用Hyperf框架进行Excel导入导出
摘要:本文将介绍如何在Hyperf框架中实现Excel文件的导入和导出功能,并给出了具体的代码示例。
关键字:Hyperf框架、Excel导入、Excel导出、代码示例
导入
首先,我们需要确保项目中安装了 phpoffice/phpspreadsheet 这个库。可以通过在终端中执行以下命令进行安装:
composer require phpoffice/phpspreadsheet
<?php declare(strict_types=1); namespace AppController; use PhpOfficePhpSpreadsheetIOFactory; class ExcelController { public function import() { $uploadedFile = $this->request->file('excel_file'); $spreadsheet = IOFactory::load($uploadedFile->getPathname()); $worksheet = $spreadsheet->getActiveSheet(); $data = $worksheet->toArray(); // 处理导入逻辑 } }
然后,在 config/routes.php 文件中添加以下路由:
use AppControllerExcelController; Router::post('/excel/import', [ExcelController::class, 'import']);
<form action="/excel/import" method="post" enctype="multipart/form-data"> <input type="file" name="excel_file"> <button type="submit">导入</button> </form>
导出
导出Excel文件主要涉及两个步骤:创建Excel文件和下载Excel文件。
use PhpOfficePhpSpreadsheetSpreadsheet; use PhpOfficePhpSpreadsheetWriterXlsx; public function export() { $spreadsheet = new Spreadsheet(); $worksheet = $spreadsheet->getActiveSheet(); // 设置表头 $worksheet->setCellValue('A1', '姓名') ->setCellValue('B1', '年龄') ->setCellValue('C1', '性别'); // 设置数据行 $data = [ ['张三', '20', '男'], ['李四', '30', '女'], ]; $row = 2; foreach ($data as $item) { $column = 'A'; foreach ($item as $value) { $worksheet->setCellValue($column . $row, $value); $column++; } $row++; } // 保存文件 $writer = new Xlsx($spreadsheet); $writer->save('storage/export.xlsx'); }
use PsrHttpMessageStreamInterface; use SymfonyComponentConsoleOutputStreamOutput; public function download() { $file = 'storage/export.xlsx'; return $this->response->withHeader('Content-Disposition', 'attachment;filename=' . $file) ->withHeader('Pragma', 'public') ->withHeader('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet') ->withHeader('Content-Length', filesize($file)) ->withBody(new StreamOutput(fopen($file, 'r'))); }
在路由文件中添加以下路由:
Router::get('/excel/download', [ExcelController::class, 'download']);
将导出的文件存储在 storage 目录下,并通过浏览器访问 /excel/download 即可实现文件下载。
总结
本文详细介绍了如何使用Hyperf框架实现Excel文件的导入和导出功能,并给出了具体的代码示例。通过简单的配置和编码,我们可以在Hyperf框架中快速实现Excel导入导出,提高开发效率。
以上就是如何使用Hyperf框架进行Excel导入导出的详细内容,更多请关注php中文网其它相关文章!
全网最新最细最实用WPS零基础入门到精通全套教程!带你真正掌握WPS办公! 内含Excel基础操作、函数设计、数据透视表等
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号