美文网首页
使用xlswriter解决phpexcel导出数据量大问题

使用xlswriter解决phpexcel导出数据量大问题

作者: why_e443 | 来源:发表于2020-11-12 16:30 被阅读0次
xlswriter 是一个 PHP C 扩展,可用于在 Excel 2007+ XLSX 文件中读取数据,插入多个工作表,写入文本、数字、公式、日期、图表、图片和超链接。

phpexcel 导出数量超过5000,可能会由于内存不足而导出失败,为了解决这个问题,可以使用,xlswrite这个php扩展来解决。

测试效率:
image

使用中文文档:https://xlswriter-docs.viest.me/zh-cn/an-zhuang

windows下载地址:https://github.com/viest/php-ext-xlswriter/releases

注意:window 注意版本、是否线程安全、操作系统位数.

github: https://github.com/viest/php-ext-xlswriter

linux下安装:

wget https://pecl.php.net/get/xlswriter-1.3.2.tgz

tar xf xlswriter-1.3.2.tgz

cd xlswriter-1.3.2

/www/server/php/72/bin/phpize

./configure --with-php-config=/www/server/php/72/bin/php-config --enable-reader

make && make install

最后修改php.ini 重启php-fpm

可用phpinfo查看扩展是否安装成功

image

使用:


set_time_limit(0);

$area = Db::table('info');

$col = [

'乡镇',

    '社区',

    '姓名',

    '手机号',

    '家庭地址',

    '身份证号',

];

$fileName = date('YmdHi').'.xlsx';

$exportData = [];

$config = ['path' => $this->getTmpDir(). '/',];

$excel  = new \Vtiful\Kernel\Excel($config);

$excel->fileName($fileName, 'sheet1')->header($col);

$area->field('uid,create_time',true)->chunk(5000,function($data)use ($exportData,$fileName,$col,$excel){

if($data){

foreach ($data as $k=>$v){

$v['card']= "'".$v['card'];

                unset($v['id']);

                array_push($exportData,array_values($v));

        }

$excel->data($exportData);

    }

});

$filePath = $excel->output();

// Set Header

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) {

}

// Delete temporary file

@unlink($filePath);

public function getTmpDir()

{

$tmp = ini_get('upload_tmp_dir');

    if ($tmp !== False && file_exists($tmp)) {

return realpath($tmp);

    }

return realpath(sys_get_temp_dir());

}

相关文章

网友评论

      本文标题:使用xlswriter解决phpexcel导出数据量大问题

      本文链接:https://www.haomeiwen.com/subject/exypbktx.html