使用PHP-Xlswriter导出数据库表至excel

提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档


一、为什么使用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,其它用法随着后续应用会逐一给大家介绍。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,我可以帮你解答。首先,你需要安装 php-xlswriter 扩展。安装方法可以参考 https://github.com/viest/php-ext-excel-export#installation。 接下来,你可以按照以下步骤实现你的功能: 1. 连接数据库PHP 中连接数据库可以使用 PDO 或者 mysqli 等扩展。这里以 PDO 为例: ``` $dsn = 'mysql:host=localhost;dbname=your_database'; $username = 'your_username'; $password = 'your_password'; try { $db = new PDO($dsn, $username, $password); } catch (PDOException $e) { echo 'Connection failed: ' . $e->getMessage(); } ``` 2. 获取数据 使用 PDO 查询数据可以这样: ``` $sql = 'SELECT * FROM cardinfo'; $stmt = $db->query($sql); $rows = $stmt->fetchAll(PDO::FETCH_ASSOC); ``` 3. 导出 Excel 文件 使用 php-xlswriter 导出 Excel 文件可以这样: ``` $writer = new XLSXWriter(); // 添加表头 $writer->writeSheetHeader('Sheet1', array_keys($rows[0])); // 添加数据 foreach ($rows as $row) { $writer->writeSheetRow('Sheet1', $row); } // 设置文件名和下载 $filename = 'cardinfo.xlsx'; header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'); header('Content-Disposition: attachment;filename="' . $filename . '"'); header('Cache-Control: max-age=0'); $writer->writeToStdOut(); ``` 完整代码: ``` $dsn = 'mysql:host=localhost;dbname=your_database'; $username = 'your_username'; $password = 'your_password'; try { $db = new PDO($dsn, $username, $password); } catch (PDOException $e) { echo 'Connection failed: ' . $e->getMessage(); } $sql = 'SELECT * FROM cardinfo'; $stmt = $db->query($sql); $rows = $stmt->fetchAll(PDO::FETCH_ASSOC); $writer = new XLSXWriter(); // 添加表头 $writer->writeSheetHeader('Sheet1', array_keys($rows[0])); // 添加数据 foreach ($rows as $row) { $writer->writeSheetRow('Sheet1', $row); } // 设置文件名和下载 $filename = 'cardinfo.xlsx'; header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'); header('Content-Disposition: attachment;filename="' . $filename . '"'); header('Cache-Control: max-age=0'); $writer->writeToStdOut(); ``` 你可以根据你的实际情况修改代码。希望能对你有所帮助。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值