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;
相关推荐
JaguarJack2 小时前
推荐 PHP 属性(Attributes) 简洁读取 API 扩展包
后端·php·服务端
BingoGo2 小时前
推荐 PHP 属性(Attributes) 简洁读取 API 扩展包
php
JaguarJack1 天前
告别 Laravel 缓慢的 Blade!Livewire Blaze 来了,为你的 Laravel 性能提速
后端·php·laravel
郑州光合科技余经理2 天前
代码展示:PHP搭建海外版外卖系统源码解析
java·开发语言·前端·后端·系统架构·uni-app·php
QQ5110082852 天前
python+springboot+django/flask的校园资料分享系统
spring boot·python·django·flask·node.js·php
WeiXin_DZbishe2 天前
基于django在线音乐数据采集的设计与实现-计算机毕设 附源码 22647
javascript·spring boot·mysql·django·node.js·php·html5
longxiangam2 天前
Composer 私有仓库搭建
php·composer
上海云盾-高防顾问2 天前
DNS异常怎么办?快速排查+解决指南
开发语言·php
ShoreKiten2 天前
关于解决本地部署sqli-labs无法安装低版本php环境问题
开发语言·php
liliangcsdn2 天前
深入探索TD3算法的推理过程
开发语言·php