search
HomePHP FrameworkSwooleHow to use Hyperf framework for Excel export

How to use Hyperf framework for Excel export

Oct 20, 2023 pm 03:15 PM
Instructionsexcel exporthyperf framework

How to use Hyperf framework for Excel export

How to use the Hyperf framework for Excel export

Exporting data to Excel is one of the needs we often encounter during the development process. Under the Hyperf framework, we can use the third-party library PhpSpreadsheet to implement the Excel export function. This article will introduce in detail how to use the Hyperf framework for Excel export and provide specific code examples.

1. Install dependent libraries

First, you need to install the PhpSpreadsheet library in the Hyperf framework project. Execute the following command in the project root directory:

composer require phpoffice/phpspreadsheet

2. Create an export class

We first create an Excel export class to encapsulate the specific implementation of the export function. Create the ExcelExporter.php file in the AppUtils directory. The code is as follows:

namespace AppUtils;

use PhpOfficePhpSpreadsheetSpreadsheet;
use PhpOfficePhpSpreadsheetWriterXlsx;

class ExcelExporter
{
    public static function export($data, $fileName, $headers, $title = null)
    {
        // 创建Excel对象
        $spreadsheet = new Spreadsheet();
        
        // 设置工作表名称
        $worksheet = $spreadsheet->getActiveSheet();
        $worksheet->setTitle($title ?: 'Sheet1');

        // 写入表头
        foreach ($headers as $key => $header) {
            $column = chr(65 + $key); // 列名,如A、B、C...
            $worksheet->setCellValue($column.'1', $header);
        }

        // 写入数据
        $row = 2; // 数据行起始行号
        foreach ($data as $item) {
            foreach ($item as $key => $value) {
                $column = chr(65 + $key); // 列名,如A、B、C...
                $worksheet->setCellValue($column.$row, $value);
            }
            $row++;
        }

        // 导出Excel文件
        $writer = new Xlsx($spreadsheet);
        $writer->save($fileName);
    }
}

In the above code, the export method receives four parameters:

  • $data: Data to be exported, two-dimensional array
  • $fileName: Exported file name, including file path
  • $headers: Header, one-dimensional array
  • $title: Worksheet name, optional parameter, default is Sheet1

3. Use the export class

After completing the writing of the export class, we can call it in the controller that needs to export data. The following is an example, taking exporting user information as an example:

<?php

namespace AppController;

use AppUtilsExcelExporter;
use HyperfHttpServerAnnotationAutoController;

/**
 * @AutoController()
 */
class UserController extends AbstractController
{
    public function export()
    {
        // 模拟数据
        $data = [
            ['id' => 1, 'name' => 'Tom', 'age' => 18],
            ['id' => 2, 'name' => 'Jerry', 'age' => 20],
            ['id' => 3, 'name' => 'Alice', 'age' => 22],
        ];

        // 表头
        $headers = ['ID', '姓名', '年龄'];

        // 文件名
        $fileName = '/path/to/export/user.xlsx';

        // 调用导出方法
        ExcelExporter::export($data, $fileName, $headers, '用户信息');

        return $this->success('导出成功');
    }
}

In the above example, we simulated a set of user information data and set the header and exported file name. After calling the export method, the Excel file is successfully exported and a prompt that the export is successful is returned.

4. Summary

Using the Hyperf framework to export Excel can be achieved by using the functions provided by the PhpSpreadsheet library and encapsulating the export class. Through the above code example, we can quickly implement the function of exporting data to Excel files. At the same time, we can also extend the export class according to actual needs to meet more complex export requirements.

The above is the detailed content of How to use Hyperf framework for Excel 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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software