如何使用hyperf框架进行excel导入导出
摘要:本文将介绍如何在hyperf框架中实现excel文件的导入和导出功能,并给出了具体的代码示例。
关键字:hyperf框架、excel导入、excel导出、代码示例
导入
首先,我们需要确保项目中安装了 phpoffice/phpspreadsheet 这个库。可以通过在终端中执行以下命令进行安装:
composer require phpoffice/phpspreadsheet
创建控制器和路由
首先,我们需要创建一个控制器来处理导入的逻辑。在 app/controller 目录下创建一个 excelcontroller.php 文件,添加以下代码:<?phpdeclare(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']);
创建视图
在 resources/views 目录中创建一个 import.blade.php 文件,添加以下表单代码:<form action="/excel/import" method="post" enctype="multipart/form-data"> <input type="file" name="excel_file"> <button type="submit">导入</button></form>
处理导入逻辑
在控制器的 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导入导出的详细内容。