Home > PHP Framework > Swoole > body text

How to use Hyperf framework for Excel import and export

王林
Release: 2023-10-25 12:13:47
Original
1837 people have browsed it

How to use Hyperf framework for Excel import and export

How to use the Hyperf framework to import and export Excel

Abstract: This article will introduce how to implement the import and export functions of Excel files in the Hyperf framework, and give specific details. code example.

Keywords: Hyperf framework, Excel import, Excel export, code examples

Import
First, we need to ensure that the phpoffice/phpspreadsheet library is installed in the project . It can be installed by executing the following command in the terminal:

composer require phpoffice/phpspreadsheet
Copy after login
  1. Creating Controllers and Routes
    First, we need to create a controller to handle the imported logic. Create an ExcelController.php file in the app/Controller directory and add the following code:
<?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();

        // 处理导入逻辑
    }
}
Copy after login

Then, in config/routes.php Add the following route to the file:

use AppControllerExcelController;

Router::post('/excel/import', [ExcelController::class, 'import']);
Copy after login
  1. Create a view
    Create a import.blade.php file in the resources/views directory , add the following form code:
<form action="/excel/import" method="post" enctype="multipart/form-data">
    <input type="file" name="excel_file">
    <button type="submit">导入</button>
</form>
Copy after login
  1. Processing import logic
    In the import method of the controller, we use the PhpSpreadsheet library to load Upload the Excel file and convert it to array format. Then, we can process the data according to actual needs.

Export
Exporting an Excel file mainly involves two steps: creating the Excel file and downloading the Excel file.

  1. Create Excel file
    In the controller, we can create an Excel file using the PhpSpreadsheet library.
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');
}
Copy after login
  1. Download Excel file
    After the export is completed, we can implement the file download function by setting the response header information.
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')));
}
Copy after login

Add the following route in the routing file:

Router::get('/excel/download', [ExcelController::class, 'download']);
Copy after login

Store the exported file in the storage directory and access it through the browser/ Excel/download can be used to download files.

Summary
This article introduces in detail how to use the Hyperf framework to implement the import and export functions of Excel files, and gives specific code examples. Through simple configuration and coding, we can quickly implement Excel import and export in the Hyperf framework to improve development efficiency.

The above is the detailed content of How to use Hyperf framework for Excel import and export. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template