提示:由于phpexcel和phpoffice导出数据会使内存溢出,所以使用php-Xlswriter# 前言
一、安装扩展
pecl install xlswriter
修改php.ini
extension = xlswriter.so
然后重启使php-fpm设置生效
二、使用步骤
1.引入库
代码如下(示例):
composer require viest/php-ext-xlswriter-ide-helper:dev-master
2.读入数据
代码如下(示例):
<?php
require __DIR__ . '/vendor/autoload.php';
$dbms='mysql'; //数据库类型
$host='127.0.0.1'; //数据库主机名
$dbName='employees'; //使用的数据库
$user='root'; //数据库连接用户名
$pass='123456'; //对应的密码
$dsn="$dbms:host=$host;dbname=$dbName";
//默认这个不是长连接,如果需要数据库长连接,需要最后加一个参数:array(PDO::ATTR_PERSISTENT => true) 变成这样:
$dbh = new \PDO($dsn, $user, $pass, array(PDO::ATTR_PERSISTENT => true));
ini_set('memory_limit','1024M');
set_time_limit(0);
$config = [
'path' => './',
];
$excel = new \Vtiful\Kernel\Excel($config);
// Init File
$fileName = 'emp.xlsx';
//固定内存模式
$excel = $excel->constMemory($fileName, 'sheet11');
$excel = $excel->header([ 'id', 'salary', 'first_name', 'last_name']);
for($i=5000;$i<=1000000;$i+=5000){
$start = $i-5000;
$limit = 5000;
$sql = "SELECT * FROM salaries order by emp_no asc limit {$start},{$limit}";
//$sql = 'SELECT * FROM employees order by emp_no asc limit 10';
//var_dump($sql);die();
//$sql = "SELECT * FROM salaries limit 10";
$sth = $dbh->prepare($sql, array(PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY));
$sth->execute();
$emps = $sth->fetchAll(PDO::FETCH_NUM);
//var_dump(count($emps));die();
//var_dump($emps);die();
$excel = $excel->data($emps);
}
// Output
$filePath = $excel->output();
结果
参考文章:http://www.884358.com/php-xlswriter
文档地址:https://xlswriter-docs.viest.me/zh-cn/an-zhuang/