我们在项目开发过程中难免会遇到导出 Excel 的需求,本文主要是介绍一款高性能的导出组件–xlswriter, 它是一个 PHP C 扩展,可用于在 Excel 2007+ XLSX 文件中写入多个工作表的文本,数字,公式和超链接,详情请点击官方地址查看
一:安装
运行环境是使用宝塔搭建
wget https://pecl.php.net/get/xlswriter-1.5.2.tgz
tar xf xlswriter-1.5.2.tgz
cd xlswriter-1.5.2
/www/server/php/71/bin/phpize
./configure --with-php-config=/www/server/php/71/bin/php-config --enable-reader
make && make install
echo "extension = xlswriter.so" >> /www/server/php/71/etc/php.ini
安装完成后重启PHP服务执行php -m
查看是否有xlswriter扩展或者运行phpinfo()
二:导出
项目是用ThinkPHP框架开发的,在导出大量数据的时候遇到了内存溢出的问题,为了解决内存溢出,查询导出数据时进行了分块处理,查询过程使用游标查询(cursor
),生成导出数据引用了yield
、导出采用的是xlswriter固定内存模式。
$count = Db::name('users')->where($where)->count();
$sheetNum = ceil($count / 20000);
set_time_limit(0);
ini_set('memory_limit', '128M');
$config = ['path' => 'uploads/'];
$excel = new \Vtiful\Kernel\Excel($config);
$fileObject = $excel->constMemory('users.xlsx', null, false);
$fileHandle = $fileObject->getHandle();
$format = new \Vtiful\Kernel\Format($fileHandle);
$boldStyle = $format->bold()->toResource();
$exportTitle = ['会员编号', '会员昵称'];
$setHeader = $fileObject->header($exportTitle);
$sheet = 1;
$user_info = UserLogic::getUserList($sheetNum, $where, 20000);
foreach ($user_info as $item) {
$setHeader->data([
[
$item[0],
$item[1]
]
]);
}
$filePath = $setHeader->output();
$fileName = 'users.xlsx';
// Set Header
header("Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
header('Content-Disposition: attachment;filename="' . $fileName . '"');
header('Cache-Control: max-age=0');
header('Content-Length: ' . filesize($filePath));
header('Content-Transfer-Encoding: binary');
header('Cache-Control: must-revalidate');
header('Pragma: public');
ob_clean();
flush();
if (copy($filePath, 'php://output') === false) {
//导出失败
}
// Delete temporary file
@unlink($filePath);
public static function getUserList($sheetNum, $where, $pagesize)
{
for ($i = 1; $i <= $sheetNum; $i++) {
$page= ($i - 1) *$pagesize;
$user_info = Db::name('users')->where($where)->field('id,sn,nickname')->limit(
$page,
$pagesize
)->cursor();
foreach ($user_info as $item) {
yield [$item['sn'], $item['nickname']];
}
}
}
三:总结
其他导出方法:
1、https://github.com/mk-j/PHP_XLSXWriter
2、PHPExcel
(PhpExcel 已经停止更新,转而代之的是 PhpSpreadsheet
)
最后:本文如果有什么描述不正确或者建议,还请各位大神留言,我将继续改正~~