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;
相关推荐
小诸葛的博客1 小时前
Flannel UDP 模式的优缺点
网络协议·udp·php
桃子酱紫君2 小时前
华为配置篇-RSTP/MSTP实验
开发语言·华为·php
JPCstorm3 小时前
客服系统重构详细计划
php
智慧地球(AI·Earth)3 小时前
OpenAI for Countries:全球AI基础设施的“技术基建革命”
开发语言·人工智能·php
zhou1853 小时前
MySQL保姆级安装教程(附资源包+5分钟极速配置+环境变量调试技巧)
java·python·mysql·php
行思理6 小时前
JIT+Opcache如何配置才能达到性能最优
c++·php·jit
皓月盈江14 小时前
Linux电脑本机使用小皮面板集成环境开发调试WEB项目
linux·php·web开发·phpstudy·小皮面板·集成环境·www.xp.cn
向哆哆1 天前
Netty在Java网络编程中的应用:实现高性能的异步通信
java·网络·php
Rverdoser1 天前
代理服务器运行速度慢是什么原因
开发语言·前端·php
森叶1 天前
从 JIT 即时编译一直讲到CGI|FastGGI|WSGI|ASGI四种协议的实现细节
python·php·web