
摘要:本文将介绍如何在Hyperf框架中实现Excel文件的导入和导出功能,并给出了具体的代码示例。
关键字:Hyperf框架、Excel导入、Excel导出、代码示例
导入
首先,我们需要确保项目中安装了 phpoffice/phpspreadsheet 这个库。可以通过在终端中执行以下命令进行安装:
composer require phpoffice/phpspreadsheet
创建控制器和路由
首先,我们需要创建一个控制器来处理导入的逻辑。在 app/Controller 目录下创建一个 ExcelController.php 文件,添加以下代码:
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']);
创建视图
在 resources/views 目录中创建一个 import.blade.php 文件,添加以下表单代码:
处理导入逻辑
在控制器的 import 方法中,我们使用 PhpSpreadsheet 库加载上传的 Excel 文件,并将其转换为数组格式。然后,我们可以根据实际需求对数据进行处理。
导出
导出Excel文件主要涉及两个步骤:创建Excel文件和下载Excel文件。
创建Excel文件
在控制器中,我们可以使用 PhpSpreadsheet 库创建一个 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');}
下载Excel文件
导出完成后,我们可以通过设置响应头信息实现文件下载的功能。
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导入导出的详细内容,更多请关注创想鸟其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/180706.html
微信扫一扫
支付宝扫一扫