提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
一、为什么使用PHP-Xlswriter?
PHPExcel 因为内存消耗过大的原因不能正常工作, 虽然可以修改内存上限, 但是导出的用时会变得非常的长,不能接受。而其在PHP7及以上版本上面的替代者PhpSpreadsheet的在内存消耗和性能方面的表现更差,几乎没有办法使用。PHP-Xlswriter 是一个 PHP C 扩展,实现的功能是用C语言实现的,性能非常出色,通过使用PHP C扩展这个桥梁,将C语言的功能扩展到PHP中来。
二、使用步骤
1.宝塔安装
在命令行模式下,切换到root用户,依次输入如下命令:
里面的74可以根据自己的PHP实际版本号修改
wget https://pecl.php.net/get/xlswriter-1.4.0.tgz
tar -zxvf xlswriter-1.4.0.tgz
cd xlswriter-1.4.0/
/www/server/php/74/bin/phpize
./configure --with-php-config=/www/server/php/74/bin/php-config
make && make install
echo "extension = xlswriter.so" >> /www/server/php/74/etc/php.ini
/etc/init.d/php-fpm-74 reload
/www/server/php/74/bin/php -m|grep -i xlswriter
2.导出mysql数据库表至excel代码示例
代码如下(示例):
<?php
function getTmpDir(): string
{
$tmp = ini_get('upload_tmp_dir');
if ($tmp !== False && file_exists($tmp)) {
return realpath($tmp);
}
return realpath(sys_get_temp_dir());
}
function export_excel($fileName, $tileArray = [], $dataArray = [])
{
$config = [
'path' => getTmpDir() . '/',
];
//$fileName = 'tutorial01.xlsx';
$excel = new \Vtiful\Kernel\Excel($config);
// fileName 会自动创建一个工作表,你可以自定义该工作表名称,工作表名称为可选参数
$fileObject = $excel->fileName($fileName, 'sheet1');
$fileHandle = $fileObject->getHandle();
$format = new \Vtiful\Kernel\Format($fileHandle);
$colorOneStyle = $format
->font('微软雅黑')
->fontSize(12)
->bold()
->align(\Vtiful\Kernel\Format::FORMAT_ALIGN_CENTER, \Vtiful\Kernel\Format::FORMAT_ALIGN_VERTICAL_CENTER)
->toResource();//标题行格式
$format = new \Vtiful\Kernel\Format($excel->getHandle());
$colorTwoStyle = $format
//->fontColor(\Vtiful\Kernel\Format::COLOR_GREEN)
->font('微软雅黑')
->fontSize(12)
->align(\Vtiful\Kernel\Format::FORMAT_ALIGN_CENTER, \Vtiful\Kernel\Format::FORMAT_ALIGN_VERTICAL_CENTER)
->toResource();//数据行格式
$filePath = $fileObject
->defaultFormat($colorOneStyle)
->header($tileArray)
->defaultFormat($colorTwoStyle)
->data($dataArray)
->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) {
// Throw exception
}
// Delete temporary file
@unlink($filePath);
$excel->close();
}
function my_db_getallex($connection,$sql)
{
$value = "";
if($connection)
{
$value = mysqli_fetch_all(mysqli_query($connection,$sql),MYSQLI_NUM);
}
return $value;
}
$connection = my_db_open();//获取数据库连接
$sql = "SELECT * from where xxx";//查询mysql数据库表的查询语句
$tileArray = array('编号','地区','企业名称');//excel 标题行
$dataArray = my_db_getallex($connection,$sql);//excel 数据行
$fileName = "xxx.xlsx";//导出文件名
export_excel($fileName, $tileArray, $dataArray);
?>
总结
以上就是今天要讲的内容,本文仅仅简单介绍了使用PHP-Xlswriter导出数据库表至excel,其它用法随着后续应用会逐一给大家介绍。