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;
相关推荐
ylscode14 小时前
PHP再曝高危安全漏洞:TLS连接缺陷可致FPM全面崩溃,OpenSSL内存损坏隐患同步浮现
开发语言·php
郑州光合科技余经理17 小时前
海外外卖平台源码改造实战——多语言核心代码实现
java·开发语言·前端·后端·mysql·架构·php
娇气的红酒21 小时前
微软对PHP支持的改进,及其它一些胡言乱语
开发语言·microsoft·php
2601_9637713721 小时前
Scaling Podcast RSS Feeds and Audio Streaming on WordPress Servers
前端·windows·php
wbs_scy21 小时前
仿 muduo 高并发服务器项目:实现轻量级日志宏,方便后续网络库调试
开发语言·php
万联WANFLOW1 天前
多分支企业组网,IP 网段到底该怎么规划
开发语言·php
WZF-Sang2 天前
网络基础——2
服务器·网络·c++·学习·网络编程·php
行思理2 天前
fastadmin 新手部分功能点
后端·php
用户3074596982072 天前
# GatewayWorker 入门指南
php
2601_963771372 天前
Optimizing Logistics and Transportation Sites on WordPress
前端·数据库·windows·php