码迷,mamicode.com
首页 > Web开发 > 详细

ThinkPhp5-PHPExcel导出数据

时间:2018-08-08 16:10:48      阅读:240      评论:0      收藏:0      [点我收藏+]

标签:tps   foreach   目录   php5   tle   ref   excel表格   主办方   reac   

PHP-Excel

标签(空格分隔): php


类库下载地址:https://codeload.github.com/PHPOffice/PHPExcel/zip/1.8
php导出excel表格数据的基本实现

实现步骤:

1 把文件夹放到extend目录下
2 import助手函数导入类
3 设置excel表头
4 填充数据

注意事项:

1 数据从第二行开始填充

ThinkPHP5示例:

# 公共方法
public function phpExcel($title, $list, $fileName)
{
    import(‘PHPExcel.Classes.PHPExcel‘);
    import(‘PHPExcel.Classes.PHPExcel.IOFactory.PHPExcel_IOFactory‘);
    $PHPExcel = new \PHPExcel;
    $PHPSheet = $PHPExcel->getActiveSheet();
    foreach ($list as $k => $v) {
        # code...
        foreach ($title as $key => $value) {
            if ($k == 0) {
                $PHPSheet->setCellValue($key.‘1‘, end($value));
            }
            $i = $k + 2;
            $PHPSheet->setCellValue($key.$i, $v[reset($value)]);
        }
    }
    $PHPWriter = \PHPExcel_IOFactory::createWriter($PHPExcel,"Excel2007");
    header("Pragma: public");
    header("Expires: 0");
    header("Cache-Control:must-revalidate, post-check=0, pre-check=0");
    header("Content-Type:application/force-download");
    header("Content-Type:application/vnd.ms-execl");
    header("Content-Type:application/octet-stream");
    header("Content-Type:application/download");;
    header(‘Content-Disposition:attachment;filename=‘.$fileName.‘.xlsx‘);
    header("Content-Transfer-Encoding:binary");
    $PHPWriter->save("php://output");
}


# 调用方法:
public function main()
{
    $title = [
        ‘A‘ => [‘id‘, ‘ID‘],
        ‘B‘ => [‘nickname‘, ‘昵称‘],
        ‘C‘ => [‘phone‘, ‘手机号‘],
        ‘D‘ => [‘avatar‘, ‘头像‘],
        ‘E‘ => [‘profile‘, ‘个人签名‘],
        ‘F‘ => [‘token‘, ‘用户唯一标识‘],
        ‘G‘ => [‘sex‘, ‘性别‘],
        ‘H‘ => [‘status‘, ‘状态‘],
        ‘I‘ => [‘to_host‘, ‘主办方id‘]
    ];
    $field = ‘id, nickname, phone, avatar, profile, token, sex, status, to_host‘;
    $list = Db::table(‘t_user‘)->field($field)->limit(10)->select();
    
    $fileName = ‘测试‘.date(‘Y-m-d‘);
    $this->excel($title, $list, $fileName);
}

ThinkPhp5-PHPExcel导出数据

标签:tps   foreach   目录   php5   tle   ref   excel表格   主办方   reac   

原文地址:https://www.cnblogs.com/yanweifeng/p/9443173.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!