php使用PHPExcel 导出数据表到Excel文件

复制代码
直接上干货:

<?php

$cards_list = Cards::find($parameters);

$objPHPExcel = new \PHPExcel();
$objPHPExcel->getProperties()->setCreator("jiequan")
    ->setLastModifiedBy("jiequan")
    ->setTitle("card List")
    ->setSubject("card List")
    ->setDescription("card List")
    ->setKeywords("excel")
    ->setCategory("result file");

$exportKeys = ["number","password","gtime"];

/*以下就是对处理Excel里的数据, 横着取数据,主要是这一步,其他基本都不要改*/
$cell = ["A","B","C","D"];
$fieldsKeyValue = array(
    "number" => "卡号",
    "password" => "密码",
    "gtime" => "领取时间",
);

foreach ($exportKeys as $k => $field) {
    $objPHPExcel->setActiveSheetIndex(0)
        ->setCellValue($cell[$k] . '1', $fieldsKeyValue[$field]);
}

foreach ($cards_list as $k => $card) {
    $num = $k + 1;
    foreach ($exportKeys as $i => $exportKey) {
        if($exportKey == "number" || $exportKey == "password") {
            $objPHPExcel->setActiveSheetIndex(0)
                ->setCellValue($cell[$i] . ($num + 1), $card->$exportKey,\PHPExcel_Cell_DataType::TYPE_STRING);
        } else {
            $objPHPExcel->setActiveSheetIndex(0)
                ->setCellValue($cell[$i] . ($num + 1), $card->$exportKey);
        }
    }

    $objPHPExcel->getActiveSheet()->getColumnDimension( 'A')->setWidth(20);
    $objPHPExcel->getActiveSheet()->getColumnDimension( 'B')->setWidth(20);
    $objPHPExcel->getActiveSheet()->getColumnDimension( 'C')->setWidth(20);
}

$objPHPExcel->getActiveSheet()->setTitle('card_List');
$objPHPExcel->getDefaultStyle()->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_LEFT);
$name = 'cardList' . "ex" . date("YmdHis",time()) . rand(1000,9999);

header("Content-Type: application/force-download");
header("Content-Type: application/octet-stream");
header("Content-Type: application/download");
header('Content-Disposition:inline;filename="'.$name.'.xls"');

$objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
$objWriter->save('php://output');
exit;
相关推荐
tommyjiatong4 小时前
解决 WordPress 必须带 index.php 才能访问及无法提交站点地图(Sitemap)的底层原理与方案
php·网站搭建·wordpress
三8445 小时前
PHP+MariaDB/MySQL搭建 社区论坛
mysql·php·mariadb
云云只是个程序马喽19 小时前
海外短剧平台搭建方案:私有化源码系统选型|云微短剧系统技术架构拆解
java·php
雅客李1 天前
2026云手机高负载压力测评 安卓云手机多开实测数据
android·智能手机·php
广州灵眸科技有限公司1 天前
xfce桌面旋转说明:基于灵眸科技EASY-EAI-Nano-TB
网络·网络协议·tcp/ip·算法·php
Risehuxyc1 天前
PHP数据类型
开发语言·php
IpdataCloud2 天前
跨区服玩家延迟高怎么办?用IP离线库自动分配到最近服务器
数据库·tcp/ip·github·php·ip
辣椒思密达2 天前
AI出海产品本地化测试:住宅IP在模拟海外用户环境中的实践价值
网络协议·tcp/ip·安全·php·苹果vision pro
bitbrowser2 天前
Claude 账号频繁被封?转向国内可直接使用的 AI 工具
开发语言·php
2501_912784082 天前
Laravel 多渠道代购订单聚合队列踩坑实战,解决跨平台漏单与同步
php·laravel·taocarts