首先说明,xlswriter是PHP的一个扩展,官网文档有介绍。也有更为详细的文档,https://xlswriter-docs.viest.me/。
Excel
你的瓶颈不再是PHP
传统的HTML格式数据转EXCEL,从浏览器直接输出不支持EXCEL2007。
所以就得安装类型PHP-EXCEL的扩展。但是十万条数据,就能把系统趴下(HTTP请求时间不允许)。
而xlswriter支持EXCEL2007,并且速度与直接输出HTML相差无几。
而且它有两种方式:
1、省时间
2、省内存
基准测试[复制自官网]
测试环境: Macbook Pro 13 inch, Intel Core i5, 16GB 2133MHz LPDDR3 Memory, 128GB SSD Storage
导出
两种内存模式导出100万行数据(单行27列,数据类型均为字符串,单个字符串长度为19)
实例:
function getTmpDir(){$tmp = ini_get('upload_tmp_dir');if ($tmp !== False && file_exists($tmp)) {return realpath($tmp);}return realpath(sys_get_temp_dir());}$filename = empty($identify) ? '1.xlsx' : '2.xlsx';$config = ['path' => $this->getTmpDir() . '/',];$fileName = $filename;$xlsxObject = new \Vtiful\Kernel\Excel($config);$fileObject = $xlsxObject->fileName($fileName);$data = array();if(!empty($excel_data) && is_array($excel_data)) {$format = new \Vtiful\Kernel\Format($xlsxObject->getHandle());$alignStyle = $format->align(\Vtiful\Kernel\Format::FORMAT_ALIGN_VERTICAL_CENTER, \Vtiful\Kernel\Format::FORMAT_ALIGN_CENTER_ACROSS)->bold()->toResource();foreach($excel_data as $id_key => $id_val) {$data[] = [$id_val['a'], $role_info['b'], $id_val['c'], $id_val['d']];}unset($excel_data);$filePath = $fileObject->header(['A列', 'B列', 'C列', 'D列'])->data($data)->setRow('A1', 22, $alignStyle)->output();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');ob_clean();flush();if (copy($filePath, 'php://output') === false) {// Throw exception}// Delete temporary file@unlink($filePath);} else {exit("没有任何数据,取消导出");}
