PHP class library for Excel spreadsheets: PHP_XLSXWriter (big data report, background operation, browser download)

insert image description here

PHP_XLSXWriter is a PHP library for generating Microsoft Excel 2007+ xlsx files. XLSX is a format for storing spreadsheet data using an open XML-based file standard for Excel 2007 and later. The PHP_XLSXWriter library provides a simple API for writing data from PHP arrays to XLSX files. It can write files containing multiple worksheets and large amounts of data, and uses autofit to handle large data volumes.

Compared with other Excel libraries, the main advantages of PHP_XLSXWriter are:

  1. High performance - PHP_XLSXWriter uses the zipArchive function to compress data files, which is fast and the generated files are relatively small.

  2. Stable operation - PHP_XLSXWriter does not need to rely on other libraries or plug-ins to run, and is more portable than other libraries.

  3. Simple and easy-to-use code - The API of PHP_XLSXWriter is simple, flexible, readable and maintainable.

  4. Support for large data sets - PHP_XLSXWriter is able to handle large amounts of data, and the adaptive processing large data volume technology adopted is very reliable when dealing with large data sets.

1. The difference between PHP_XLSXWriter and PHPExcel

Both PHP_XLSXWriter and PHPExcel are PHP class libraries used to operate Excel spreadsheets. Their differences are mainly reflected in the following aspects:

  1. Speed ​​and memory consumption

Compared with PHPExcel, PHP_XLSXWriter is faster when operating a large amount of data, and it also saves memory resources.

  1. external dependencies

PHPExcel needs to rely on third-party libraries such as LibreOffice or OpenOffice to operate Excel files, while PHP_XLSXWriter does not require external dependencies and can directly generate spreadsheet files in OpenXML format.

  1. Functionality and Flexibility

PHPExcel is very rich in functions, supports reading and writing operations in various Excel formats, and can also handle some advanced Excel operations, such as formula calculations. In contrast, although PHP_XLSXWriter is not as powerful as PHPExcel, its design is more flexible and can easily process and format data.

  1. developer support

PHPExcel has announced the end of maintenance and support since 2018. Although it can still be used, it may encounter some compatibility and security issues in the future. In contrast, PHP_XLSXWriter is still actively maintained and developed, and there will be more functional and performance improvements in the future.

To sum up, if you need a high degree of flexibility and performance for Excel file operations, you can choose PHP_XLSXWriter. If you need to process complex Excel files and use advanced Excel operations, you can use PHPExcel. However, considering that PHPExcel has stopped development and support, it is recommended to use a new class library such as PhpSpreadsheet.

Two, the use of PHP_XLSXWriter

1. Steps to use

PHP_XLSXWriter is a PHP class library for generating Microsoft Excel OpenXML format spreadsheets (xlsx). Using the PHP_XLSXWriter library can be very convenient to generate Excel spreadsheets, and supports multiple data types and Excel's various formatting options. Here are some basic steps to use PHP_XLSXWriter:

  1. Download and install the PHP_XLSXWriter class library: Portal . This class library can be downloaded on Github, and the downloaded files can be placed anywhere under the project.

  2. Create an instance of XLSXWriter. code show as below:

require_once 'path/to/XLSXWriter.php';
$writer = new XLSXWriter();
  1. Set the basic information written to the Excel spreadsheet, such as title, worksheet name, etc. The sample code is as follows:
$writer->setTitle('My Excel Document');
$writer->setSubject('Document Subject');
$writer->setAuthor('Author Name');
$writer->setDescription('Document Description');
$writer->setKeywords('keywords, go, here');

$sheet_name = 'Sheet1';
$writer->writeSheetHeader($sheet_name, array('Column 1'=> 'string', 'Column 2'=> 'string', 'Column 3'=> 'string', 'Column 4'=> 'string', 'Column 5'=> 'string', 'Column 6'=> 'string'));
  1. Write data to an Excel spreadsheet. The sample code is as follows:
$data = array(
       array('Value 1-1', 'Value 1-2', 'Value 1-3', 'Value 1-4', 'Value 1-5', 'Value 1-6'),
       array('Value 2-1', 'Value 2-2', 'Value 2-3', 'Value 2-4', 'Value 2-5', 'Value 2-6'),
       array('Value 3-1', 'Value 3-2', 'Value 3-3', 'Value 3-4', 'Value 3-5', 'Value 3-6'),
       array('Value 4-1', 'Value 4-2', 'Value 4-3', 'Value 4-4', 'Value 4-5', 'Value 4-6'),
       array('Value 5-1', 'Value 5-2', 'Value 5-3', 'Value 5-4', 'Value 5-5', 'Value 5-6'),
);

foreach($data as $row) {
    
    
       $writer->writeSheetRow($sheet_name, $row);
}
  1. Save the Excel spreadsheet. The sample code is as follows:
$filename = 'my_excel_file';
$writer->writeToFile($filename . '.xlsx');

The above is the basic process of using the PHP_XLSXWriter library to generate Excel files. You can adjust the codes of each step according to actual needs to achieve the effect you want.

2. Background download

Function encapsulation is the practice of combining a series of related operations into a function and providing a unified interface to the outside world. Its main benefits are as follows:

  1. Improve code reusability and maintainability

Abstract some common operations into functions and organize the code in a modular way, which helps to improve the reusability and maintainability of the code, because different code areas can share the same function without having to write it repeatedly.

  1. Improve code readability

Using the function name to describe the function function can improve the readability of the code and make the code easier to understand and maintain. Through encapsulation, the code can be modularized, which is easy to understand and maintain.

  1. Improve code encapsulation and security

Encapsulation can hide internal details and only expose necessary interfaces, improving the encapsulation and security of code. Encapsulation can also ensure data integrity by restricting access to internal data, thereby avoiding the danger of data being maliciously tampered with.

  1. Simplify code implementation and maintenance

By encapsulating some common operations, the complexity of code implementation and maintenance can be greatly simplified, the chance of errors can be reduced, and developers can focus more on the implementation of business logic.

In conclusion, function encapsulation is a great way to help write efficient, readable, maintainable, robust and safe code.

/*封装函数
$data,array,数据
$header,标头名称
*/
function makeExcel($data, $header)
{
    
    
    require_once "libs/xlsxwriter/xlsxwriter.class.php";
    //实例化
    $writer = new XLSXWriter();
    //文件属性
    $writer->setTitle('My Excel Document');
    $writer->setSubject('Document Subject');
    $writer->setAuthor('Author Name');
    $writer->setDescription('Document Description');
    $writer->setKeywords('keywords, go, here');

    $sheet_name = 'Sheet1';
    $writer->writeSheetHeader($sheet_name, $header);

    foreach ($data as $row) {
    
    
        $writer->writeSheetRow($sheet_name, $row);
    }

    $filename = md5(time()) . '.xlsx';
    $writer->writeToFile('upload/' . $filename);
}

//表头
$header = array('序号' => 'int', '姓名' => 'string', '性别' => 'string', '单位' => 'string', '职务' => 'string', '学历' => 'string');
//二维数组
$len = 10000;
$data = array();
for ($j = 0; $j < $len; $j++) {
    
    
    $data[$j] = array($j + 1, '姓名' . $j, '性别' . $j, '单位' . $j, '职务' . $j, '学历' . $j);
}
//生成表格
makeExcel($data, $header);

3. Browser download

You can download the Excel file generated by PHP_XLSXWriter directly through the browser through the following code:

// 导入 PHP_XLSXWriter 库
require 'path/to/PHP_XLSXWriter.php';

// 创建 XLSXWriter 实例
$writer = new XLSXWriter();

// 添加数据到 Excel 文档
$data = array(
   array('姓名', '年龄', '城市'),
   array('张三', 28, '北京'),
   array('李四', 22, '上海'),
   array('王五', 31, '广州')
);

$writer->writeSheet($data);

// 定义下载的文件名
$filename = 'example.xlsx';

// 告诉浏览器输出的内容类型为 Excel
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');

// 告诉浏览器文件的大小和名称
header('Content-Disposition: attachment;filename="'. $filename .'"');

// 将 Excel 文件输出到浏览器
$writer->writeToStdOut();
exit();

In the example above, we first created an XLSXWriterinstance and added some data. Then, we use the PHP header()function to tell the browser that the output content type is Excel, and specify the name of the downloaded file. Finally, we output the Excel file to the browser and stop the script from running with exit()the function .

In this way, when the user clicks the download link, the browser will start a download operation and save the generated Excel file to the local disk.

4. Encapsulation function

Let the function support background running and browser downloading at the same time.

/*封装函数
* $data,array,数据;
* $header,array,标头名称;
* $export,输出方式0后台运行1浏览器下载;
*/
function makeExcel($data, $header, $export = 0)
{
    
    
    require_once "libs/xlsxwriter/xlsxwriter.class.php";
    //实例化
    $writer = new XLSXWriter();
    //文件属性
    $writer->setTitle('My Excel Document');
    $writer->setSubject('Document Subject');
    $writer->setAuthor('Author Name');
    $writer->setDescription('Document Description');
    $writer->setKeywords('keywords, go, here');
    $sheet_name = 'Sheet1';
    $writer->writeSheetHeader($sheet_name, $header);
    
    //文件名称
    $filename = md5(time()) . '.xlsx';
    //设置下载方式
    if ($export == 0) {
    
    
        foreach ($data as $row) {
    
    
            $writer->writeSheetRow($sheet_name, $row);
        }
        $writer->writeToFile('upload/' . $filename);
    } else {
    
    
        $writer->writeSheet($data);
        // 告诉浏览器输出的内容类型为 Excel
        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        // 告诉浏览器文件的大小和名称
        header('Content-Disposition: attachment;filename="' . $filename . '"');
        // 将 Excel 文件输出到浏览器
        $writer->writeToStdOut();
        exit();
    }
}

@leak time sometimes

Guess you like

Origin blog.csdn.net/weixin_41290949/article/details/131004724