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;
相关推荐
Q_Q19632884752 小时前
python+django/flask+vue的多媒体素材管理系统
spring boot·python·django·flask·node.js·php
网安老伯4 小时前
什么是网络安全?网络安全包括哪几个方面?学完能做一名黑客吗?
linux·数据库·python·web安全·网络安全·php·xss
梦想要有4 小时前
盲盒爬塔小程序
php
悦悦子a啊5 小时前
[Java]实验--编写TCP客户端程序
java·tcp/ip·php
元素之窗7 小时前
MATLAB 的输入与输出:一篇速查博客
开发语言·matlab·php
Q_Q5110082858 小时前
python+django/flask医药垃圾分类管理系统
spring boot·python·django·flask·node.js·php
十八岁牛爷爷8 小时前
快速入门从零开始一个qt程序开发,熟悉最主要的开发组件应用
数据库·qt·php
Q_Q5110082859 小时前
python+django/flask创新型产品提前购系统
spring boot·python·django·flask·node.js·php
Q_Q19632884759 小时前
python+django/flask+vue的基于协同过滤算法的体育商品推荐系统
spring boot·python·django·flask·node.js·php
4***579 小时前
PHP进阶-在Ubuntu上搭建LAMP环境教程
开发语言·ubuntu·php