search
HomeBackend DevelopmentPHP TutorialIntroduction to how phpspreadsheet exports data to Excel (code example)

This article brings you an introduction to the method of exporting data to Excel using phpspreadsheet (code example). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

Before we used PHP to export Excel data, we used the PHPExcel library, but phpoffice has officially announced that PHPExcel has been abandoned and is no longer maintained. It is recommended to use phpspreadsheet, as shown in the figure below

Introduction to how phpspreadsheet exports data to Excel (code example)

We can install phpspreadsheet through composer

Introduction to how phpspreadsheet exports data to Excel (code example)

composer require phpoffice/phpspreadsheet

Use phpspreadsheet to export student information to the browser code example

/**
 * 输出到浏览器(需要设置header头)
 * @param string $fileName 文件名
 * @param string $fileType 文件类型
 */
function excelBrowserExport($fileName, $fileType) {

    //文件名称校验
    if(!$fileName) {
        trigger_error('文件名不能为空', E_USER_ERROR);
    }

    //Excel文件类型校验
    $type = ['Excel2007', 'Xlsx', 'Excel5', 'xls'];
    if(!in_array($fileType, $type)) {
        trigger_error('未知文件类型', E_USER_ERROR);
    }

    if($fileType == 'Excel2007' || $fileType == 'Xlsx') {
        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        header('Content-Disposition: attachment;filename="'.$fileName.'.xlsx"');
        header('Cache-Control: max-age=0');
    } else { //Excel5
        header('Content-Type: application/vnd.ms-excel');
        header('Content-Disposition: attachment;filename="'.$fileName.'.xls"');
        header('Cache-Control: max-age=0');
    }
}

$data = [
    [1, 'jack', 10],
    [2, 'mike', 12],
    [3, 'jane', 21],
    [4, 'paul', 26],
    [5, 'kitty', 25],
    [6, 'yami', 60],
];

$title = ['id', 'name', 'age'];

$spreadsheet = new Spreadsheet();
$worksheet = $spreadsheet->getActiveSheet();

//设置工作表标题名称
$worksheet->setTitle('工作表格1');

//表头
//设置单元格内容
foreach ($title as $key => $value) {
    $worksheet->setCellValueByColumnAndRow($key+1, 1, $value);
}

$row = 2; //从第二行开始
foreach ($data as $item) {
    $column = 1;

    foreach ($item as $value) {
        $worksheet->setCellValueByColumnAndRow($column, $row, $value);
        $column++;
    }
    $row++;
}


$fileName = '学生信息';
$fileType = 'Xlsx';

//1.下载到服务器
//$writer = IOFactory::createWriter($spreadsheet, 'Xlsx');
//$writer->save($fileName.'.'.$fileType);

//2.输出到浏览器
$writer = IOFactory::createWriter($spreadsheet, 'Xlsx'); //按照指定格式生成Excel文件
excelBrowserExport($fileName, 'Xlsx');
$writer->save('php://output');

The export result is as shown in the figure :

Introduction to how phpspreadsheet exports data to Excel (code example)

The above is the detailed content of Introduction to how phpspreadsheet exports data to Excel (code example). For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:博客园. If there is any infringement, please contact admin@php.cn delete
How do you create and use an interface in PHP?How do you create and use an interface in PHP?Apr 30, 2025 pm 03:40 PM

The article explains how to create, implement, and use interfaces in PHP, focusing on their benefits for code organization and maintainability.

What is the difference between crypt() and password_hash()?What is the difference between crypt() and password_hash()?Apr 30, 2025 pm 03:39 PM

The article discusses the differences between crypt() and password_hash() in PHP for password hashing, focusing on their implementation, security, and suitability for modern web applications.

How can you prevent Cross-Site Scripting (XSS) in PHP?How can you prevent Cross-Site Scripting (XSS) in PHP?Apr 30, 2025 pm 03:38 PM

Article discusses preventing Cross-Site Scripting (XSS) in PHP through input validation, output encoding, and using tools like OWASP ESAPI and HTML Purifier.

What is autoloading in PHP?What is autoloading in PHP?Apr 30, 2025 pm 03:37 PM

Autoloading in PHP automatically loads class files when needed, improving performance by reducing memory use and enhancing code organization. Best practices include using PSR-4 and organizing code effectively.

What are PHP streams?What are PHP streams?Apr 30, 2025 pm 03:36 PM

PHP streams unify handling of resources like files, network sockets, and compression formats via a consistent API, abstracting complexity and enhancing code flexibility and efficiency.

What is the maximum size of a file that can be uploaded using PHP ?What is the maximum size of a file that can be uploaded using PHP ?Apr 30, 2025 pm 03:35 PM

The article discusses managing file upload sizes in PHP, focusing on the default limit of 2MB and how to increase it by modifying php.ini settings.

What is Nullable types in PHP ?What is Nullable types in PHP ?Apr 30, 2025 pm 03:34 PM

The article discusses nullable types in PHP, introduced in PHP 7.1, allowing variables or parameters to be either a specified type or null. It highlights benefits like improved readability, type safety, and explicit intent, and explains how to declar

What is the difference between the unset() and unlink() functions ?What is the difference between the unset() and unlink() functions ?Apr 30, 2025 pm 03:33 PM

The article discusses the differences between unset() and unlink() functions in programming, focusing on their purposes and use cases. Unset() removes variables from memory, while unlink() deletes files from the filesystem. Both are crucial for effec

See all articles

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 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool