


How to use xlswriter in PHP to import and export big data? (detailed explanation)
How does PHP use xlswriter to import and export big data? The following article will introduce to you the method of importing and exporting PHP big data xlswriter (optimal dataization). I hope it will be helpful to you!
This article introduces the Vtiful\Kernel\Excel class based on the PHP extension xlswriter, which can support unlimited levels of complex header export! We may continue to update and optimize in the future
1. Prepare xlswriter extension
1. Windows system:
Go to the PECL website to download the ddl file that matches your local PHP environment. Download address: https://pecl.php.net/package/xlswriter, and copy it to the PHP extension directory ext folder, modify the php.ini file,
Add this line
extension=xlswriter
2. Linux system:
Use the command to install
pecl install xlswriter
php configuration file addition
extension = xlswriter.so
Restart: php nginx View PHP installation xlswriter extension
##2. Encapsulate export class files (here comes the key point)<?php
namespace App\Services;
use Vtiful\Kernel\Excel;
class MultiFloorXlsWriterService
{
// 默认宽度
private $defaultWidth = 16;
// 默认导出格式
private $exportType = '.xlsx';
// 表头最大层级
private $maxHeight = 1;
// 文件名
private $fileName = null;
private $xlsObj;
private $fileObject;
private $format;
/**
* MultiFloorXlsWriterService constructor.
* @throws \App\Exceptions\ApiException
*/
public function __construct()
{
// 文件默认输出地址
$path = base_path().'/public/uploads/excel';
$config = [
'path' => $path
];
$this->xlsObj = (new \Vtiful\Kernel\Excel($config));
}
/**
* 设置文件名
* @param string $fileName
* @param string $sheetName
* @author LWW
*/
public function setFileName(string $fileName = '', string $sheetName = 'Sheet1')
{
$fileName = empty($fileName) ? (string)time() : $fileName;
$fileName .= $this->exportType;
$this->fileName = $fileName;
$this->fileObject = $this->xlsObj->fileName($fileName, $sheetName);
$this->format = (new \Vtiful\Kernel\Format($this->fileObject->getHandle()));
}
/**
* 设置表头
* @param array $header
* @param bool $filter
* @throws \Exception
* @author LWW
*/
public function setHeader(array $header, bool $filter = false)
{
if (empty($header)) {
throw new \Exception('表头数据不能为空');
}
if (is_null($this->fileName)) {
self::setFileName(time());
}
// 获取单元格合并需要的信息
$colManage = self::setHeaderNeedManage($header);
// 完善单元格合并信息
$colManage = self::completeColMerge($colManage);
// 合并单元格
self::queryMergeColumn($colManage, $filter);
}
/**
* 填充文件数据
* @param array $data
* @author LWW
*/
public function setData(array $data)
{
foreach ($data as $row => $datum) {
foreach ($datum as $column => $value) {
$this->fileObject->insertText($row + $this->maxHeight, $column, $value);
}
}
}
/**
* 添加Sheet
* @param string $sheetName
* @author LWW
*/
public function addSheet(string $sheetName)
{
$this->fileObject->addSheet($sheetName);
}
/**
* 保存文件至服务器
* @return mixed
* @author LWW
*/
public function output()
{
return $this->fileObject->output();
}
/**
* 输出到浏览器
* @param string $filePath
* @throws \Exception
* @author LWW
*/
public function excelDownload(string $filePath)
{
$fileName = $this->fileName;
$userBrowser = $_SERVER['HTTP_USER_AGENT'];
if (preg_match('/MSIE/i', $userBrowser)) {
$fileName = urlencode($fileName);
} else {
$fileName = iconv('UTF-8', 'GBK//IGNORE', $fileName);
}
header("Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
header('Content-Disposition: attachment;filename="' . $fileName . '"');
header('Content-Length: ' . filesize($filePath));
header('Content-Transfer-Encoding: binary');
header('Cache-Control: must-revalidate');
header('Cache-Control: max-age=0');
header('Pragma: public');
if (ob_get_contents()) {
ob_clean();
}
flush();
if (copy($filePath, 'php://output') === false) {
throw new \Exception($filePath . '地址出问题了');
}
// 删除本地文件
@unlink($filePath);
exit();
}
/**
* 组装单元格合并需要的信息
* @param array $header
* @param int $col
* @param int $cursor
* @param array $colManage
* @param null $parent
* @param array $parentList
* @return array
* @throws \Exception
* @author LWW
*/
private function setHeaderNeedManage(array $header,int $col = 1,int &$cursor = 0,array &$colManage = [], $parent = null,array $parentList = [])
{
foreach ($header as $head) {
if (empty($head['title'])) {
throw new \Exception('表头数据格式有误');
}
if (is_null($parent)) {
// 循环初始化
$parentList = [];
$col = 1;
} else {
// 递归进入,高度和父级集合通过相同父级条件从已有数组中获取,避免递归增加与实际数据不符
foreach ($colManage as $value) {
if ($value['parent'] == $parent) {
$parentList = $value['parentList'];
$col = $value['height'];
break;
}
}
}
// 单元格标识
$column = $this->getColumn($cursor) . $col;
// 组装单元格需要的各种信息
$colManage[$column] = [
'title' => $head['title'], // 标题
'cursor' => $cursor, // 游标
'cursorEnd' => $cursor, // 结束游标
'height' => $col, // 高度
'width' => $this->defaultWidth, // 宽度
'mergeStart' => $column, // 合并开始标识
'hMergeEnd' => $column, // 横向合并结束标识
'zMergeEnd' => $column, // 纵向合并结束标识
'parent' => $parent, // 父级标识
'parentList' => $parentList, // 父级集合
];
if (isset($head['children']) && !empty($head['children']) && is_array($head['children'])) {
// 有下级,高度加一
$col += 1;
// 当前标识加入父级集合
$parentList[] = $column;
$this->setHeaderNeedManage($head['children'], $col, $cursor, $colManage, $column, $parentList);
} else {
// 没有下级,游标加一
$cursor += 1;
}
}
return $colManage;
}
/**
* 完善单元格合并信息
* @param array $colManage
* @return mixed
* @author LWW
*/
private function completeColMerge(array $colManage)
{
$this->maxHeight = max(array_column($colManage, 'height'));
$parentManage = array_column($colManage, 'parent');
foreach ($colManage as $index => $value) {
// 设置横向合并结束范围:存在父级集合,把所有父级的横向合并结束范围设置为当前单元格
if (!is_null($value['parent']) && !empty($value['parentList'])) {
foreach ($value['parentList'] as $parent) {
$colManage[$parent]['hMergeEnd'] = self::getColumn($value['cursor']) . $colManage[$parent]['height'];
$colManage[$parent]['cursorEnd'] = $value['cursor'];
}
}
// 设置纵向合并结束范围:当前高度小于最大高度 且 不存在以当前单元格标识作为父级的项
$checkChildren = array_search($index, $parentManage);
if ($value['height'] < $this->maxHeight && !$checkChildren) {
$colManage[$index]['zMergeEnd'] = self::getColumn($value['cursor']) . $this->maxHeight;
}
}
return $colManage;
}
/**
* 合并单元格
* @param array $colManage
* @param bool $filter
* @author LWW
*/
private function queryMergeColumn(array $colManage,bool $filter)
{
foreach ($colManage as $value) {
$this->fileObject->mergeCells("{$value['mergeStart']}:{$value['zMergeEnd']}", $value['title']);
$this->fileObject->mergeCells("{$value['mergeStart']}:{$value['hMergeEnd']}", $value['title']);
// 设置单元格需要的宽度
if ($value['cursor'] != $value['cursorEnd']) {
$value['width'] = ($value['cursorEnd'] - $value['cursor'] + 1) * $this->defaultWidth;
}
// 设置列单元格样式
$toColumnStart = self::getColumn($value['cursor']);
$toColumnEnd = self::getColumn($value['cursorEnd']);
$this->fileObject->setColumn("{$toColumnStart}:{$toColumnEnd}", $value['width']);
}
// 是否开启过滤选项
if ($filter) {
// 获取最后的单元格标识
$filterEndColumn = self::getColumn(end($colManage)['cursorEnd']) . $this->maxHeight;
$this->fileObject->autoFilter("A1:{$filterEndColumn}");
}
}
/**
* 获取单元格列标识
* @param int $num
* @return string
* @author LWW
*/
private function getColumn(int $num)
{
return Excel::stringFromColumnIndex($num);
}
}
Copy after login
<?php namespace App\Services; use Vtiful\Kernel\Excel; class MultiFloorXlsWriterService { // 默认宽度 private $defaultWidth = 16; // 默认导出格式 private $exportType = '.xlsx'; // 表头最大层级 private $maxHeight = 1; // 文件名 private $fileName = null; private $xlsObj; private $fileObject; private $format; /** * MultiFloorXlsWriterService constructor. * @throws \App\Exceptions\ApiException */ public function __construct() { // 文件默认输出地址 $path = base_path().'/public/uploads/excel'; $config = [ 'path' => $path ]; $this->xlsObj = (new \Vtiful\Kernel\Excel($config)); } /** * 设置文件名 * @param string $fileName * @param string $sheetName * @author LWW */ public function setFileName(string $fileName = '', string $sheetName = 'Sheet1') { $fileName = empty($fileName) ? (string)time() : $fileName; $fileName .= $this->exportType; $this->fileName = $fileName; $this->fileObject = $this->xlsObj->fileName($fileName, $sheetName); $this->format = (new \Vtiful\Kernel\Format($this->fileObject->getHandle())); } /** * 设置表头 * @param array $header * @param bool $filter * @throws \Exception * @author LWW */ public function setHeader(array $header, bool $filter = false) { if (empty($header)) { throw new \Exception('表头数据不能为空'); } if (is_null($this->fileName)) { self::setFileName(time()); } // 获取单元格合并需要的信息 $colManage = self::setHeaderNeedManage($header); // 完善单元格合并信息 $colManage = self::completeColMerge($colManage); // 合并单元格 self::queryMergeColumn($colManage, $filter); } /** * 填充文件数据 * @param array $data * @author LWW */ public function setData(array $data) { foreach ($data as $row => $datum) { foreach ($datum as $column => $value) { $this->fileObject->insertText($row + $this->maxHeight, $column, $value); } } } /** * 添加Sheet * @param string $sheetName * @author LWW */ public function addSheet(string $sheetName) { $this->fileObject->addSheet($sheetName); } /** * 保存文件至服务器 * @return mixed * @author LWW */ public function output() { return $this->fileObject->output(); } /** * 输出到浏览器 * @param string $filePath * @throws \Exception * @author LWW */ public function excelDownload(string $filePath) { $fileName = $this->fileName; $userBrowser = $_SERVER['HTTP_USER_AGENT']; if (preg_match('/MSIE/i', $userBrowser)) { $fileName = urlencode($fileName); } else { $fileName = iconv('UTF-8', 'GBK//IGNORE', $fileName); } header("Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"); header('Content-Disposition: attachment;filename="' . $fileName . '"'); header('Content-Length: ' . filesize($filePath)); header('Content-Transfer-Encoding: binary'); header('Cache-Control: must-revalidate'); header('Cache-Control: max-age=0'); header('Pragma: public'); if (ob_get_contents()) { ob_clean(); } flush(); if (copy($filePath, 'php://output') === false) { throw new \Exception($filePath . '地址出问题了'); } // 删除本地文件 @unlink($filePath); exit(); } /** * 组装单元格合并需要的信息 * @param array $header * @param int $col * @param int $cursor * @param array $colManage * @param null $parent * @param array $parentList * @return array * @throws \Exception * @author LWW */ private function setHeaderNeedManage(array $header,int $col = 1,int &$cursor = 0,array &$colManage = [], $parent = null,array $parentList = []) { foreach ($header as $head) { if (empty($head['title'])) { throw new \Exception('表头数据格式有误'); } if (is_null($parent)) { // 循环初始化 $parentList = []; $col = 1; } else { // 递归进入,高度和父级集合通过相同父级条件从已有数组中获取,避免递归增加与实际数据不符 foreach ($colManage as $value) { if ($value['parent'] == $parent) { $parentList = $value['parentList']; $col = $value['height']; break; } } } // 单元格标识 $column = $this->getColumn($cursor) . $col; // 组装单元格需要的各种信息 $colManage[$column] = [ 'title' => $head['title'], // 标题 'cursor' => $cursor, // 游标 'cursorEnd' => $cursor, // 结束游标 'height' => $col, // 高度 'width' => $this->defaultWidth, // 宽度 'mergeStart' => $column, // 合并开始标识 'hMergeEnd' => $column, // 横向合并结束标识 'zMergeEnd' => $column, // 纵向合并结束标识 'parent' => $parent, // 父级标识 'parentList' => $parentList, // 父级集合 ]; if (isset($head['children']) && !empty($head['children']) && is_array($head['children'])) { // 有下级,高度加一 $col += 1; // 当前标识加入父级集合 $parentList[] = $column; $this->setHeaderNeedManage($head['children'], $col, $cursor, $colManage, $column, $parentList); } else { // 没有下级,游标加一 $cursor += 1; } } return $colManage; } /** * 完善单元格合并信息 * @param array $colManage * @return mixed * @author LWW */ private function completeColMerge(array $colManage) { $this->maxHeight = max(array_column($colManage, 'height')); $parentManage = array_column($colManage, 'parent'); foreach ($colManage as $index => $value) { // 设置横向合并结束范围:存在父级集合,把所有父级的横向合并结束范围设置为当前单元格 if (!is_null($value['parent']) && !empty($value['parentList'])) { foreach ($value['parentList'] as $parent) { $colManage[$parent]['hMergeEnd'] = self::getColumn($value['cursor']) . $colManage[$parent]['height']; $colManage[$parent]['cursorEnd'] = $value['cursor']; } } // 设置纵向合并结束范围:当前高度小于最大高度 且 不存在以当前单元格标识作为父级的项 $checkChildren = array_search($index, $parentManage); if ($value['height'] < $this->maxHeight && !$checkChildren) { $colManage[$index]['zMergeEnd'] = self::getColumn($value['cursor']) . $this->maxHeight; } } return $colManage; } /** * 合并单元格 * @param array $colManage * @param bool $filter * @author LWW */ private function queryMergeColumn(array $colManage,bool $filter) { foreach ($colManage as $value) { $this->fileObject->mergeCells("{$value['mergeStart']}:{$value['zMergeEnd']}", $value['title']); $this->fileObject->mergeCells("{$value['mergeStart']}:{$value['hMergeEnd']}", $value['title']); // 设置单元格需要的宽度 if ($value['cursor'] != $value['cursorEnd']) { $value['width'] = ($value['cursorEnd'] - $value['cursor'] + 1) * $this->defaultWidth; } // 设置列单元格样式 $toColumnStart = self::getColumn($value['cursor']); $toColumnEnd = self::getColumn($value['cursorEnd']); $this->fileObject->setColumn("{$toColumnStart}:{$toColumnEnd}", $value['width']); } // 是否开启过滤选项 if ($filter) { // 获取最后的单元格标识 $filterEndColumn = self::getColumn(end($colManage)['cursorEnd']) . $this->maxHeight; $this->fileObject->autoFilter("A1:{$filterEndColumn}"); } } /** * 获取单元格列标识 * @param int $num * @return string * @author LWW */ private function getColumn(int $num) { return Excel::stringFromColumnIndex($num); } }
3. Usage example
The code is as follows/** * 导出测试 * @author LWW */ public function export() { $header = [ [ 'title' => '一级表头1', 'children' => [ [ 'title' => '二级表头1', ], [ 'title' => '二级表头2', ], [ 'title' => '二级表头3', ], ] ], [ 'title' => '一级表头2' ], [ 'title' => '一级表头3', 'children' => [ [ 'title' => '二级表头1', 'children' => [ [ 'title' => '三级表头1', ], [ 'title' => '三级表头2', ], ] ], [ 'title' => '二级表头2', ], [ 'title' => '二级表头3', 'children' => [ [ 'title' => '三级表头1', 'children' => [ [ 'title' => '四级表头1', 'children' => [ [ 'title' => '五级表头1' ], [ 'title' => '五级表头2' ] ] ], [ 'title' => '四级表头2' ] ] ], [ 'title' => '三级表头2', ], ] ] ] ], [ 'title' => '一级表头4', ], [ 'title' => '一级表头5', ], ]; $data= []; // header头规则 title表示列标题,children表示子列,没有子列children可不写或为空 for ($i = 0; $i < 100; $i++) { $data[] = [ '这是第'. $i .'行测试', '这是第'. $i .'行测试', '这是第'. $i .'行测试', '这是第'. $i .'行测试', '这是第'. $i .'行测试', '这是第'. $i .'行测试', '这是第'. $i .'行测试', '这是第'. $i .'行测试', '这是第'. $i .'行测试', '这是第'. $i .'行测试', '这是第'. $i .'行测试', '这是第'. $i .'行测试', '这是第'. $i .'行测试', ]; } $fileName = '很厉害的文件导出类'; $xlsWriterServer = new MultiFloorXlsWriterService(); $xlsWriterServer->setFileName($fileName, '这是Sheet1别名'); $xlsWriterServer->setHeader($header, true); $xlsWriterServer->setData($data); $xlsWriterServer->addSheet('这是Sheet2别名'); $xlsWriterServer->setHeader($header); //这里可以使用新的header $xlsWriterServer->setData($data); // 这里也可以根据新的header定义数据格式 $filePath = $xlsWriterServer->output(); // 保存到服务器 $xlsWriterServer->excelDownload($filePath); // 输出到浏览器 }
PHP video tutorial》
The above is the detailed content of How to use xlswriter in PHP to import and export big data? (detailed explanation). For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.
