search
HomePHP FrameworkSwooleHow to use Hyperf framework for Excel import and export

How to use Hyperf framework for Excel import and export

Oct 25, 2023 pm 12:13 PM
excelhyperfImport and Export

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
  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();

        // 处理导入逻辑
    }
}

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

use AppControllerExcelController;

Router::post('/excel/import', [ExcelController::class, 'import']);
  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>
  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');
}
  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')));
}

Add the following route in the routing file:

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

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!

Statement
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft