phpexcel导出

jerry thinkphp 2015年11月19日 收藏
这里只粘贴了使用的代码,里面需要引用phpexcel,在上面搜索phpexcel就有很多下载的
/**
     * 客户导出
     *
     **/
    public function excelExport($customerList=false){
        C('OUTPUT_ENCODE', false);
        import("ORG.PHPExcel.PHPExcel");
        $objPHPExcel = new PHPExcel();    
        $objProps = $objPHPExcel->getProperties();
        $objPHPExcel->setActiveSheetIndex(0);     
        $objActSheet = $objPHPExcel->getActiveSheet(); 
           
        $objActSheet->setTitle('Sheet1');
        $ascii = 65;
        $cv = '';
        //联系人字段
        $contacts_fields_list = array();
        $contacts_fields_list[0]['field'] = 'name';
        $contacts_fields_list[0]['name'] = '用户名';
        $contacts_fields_list[1]['field'] = 'telephone';
        $contacts_fields_list[1]['name'] = '电话';
        
        foreach($contacts_fields_list as $field){
            $objActSheet->setCellValue($cv.chr($ascii).'1', $field['name']);
            $ascii++;
            if($ascii == 91){
                $ascii = 65;
                $cv .= chr(strlen($cv)+65);
            }
        }
        
        /*$where['owner_role_id'] = array('in',implode(',', getSubRoleId()));
        $where['is_deleted'] = 0;*/
        $list = M('user')->select();
        $ascii = 65;
        $cv = '';
        $i = 2;
        foreach($list as $val){
            foreach($contacts_fields_list as $valu){
                //防止使用科学计数法,在数据前加空格
                if($valu['field'] == 'telephone' || $valu['field'] =='qq'){
                    $objActSheet->setCellValue($cv.chr($ascii).$i, ' '.$val[$valu['field']]);
                }else{
                    $objActSheet->setCellValue($cv.chr($ascii).$i, $val[$valu['field']]);
                }
                
                $ascii++;
                if($ascii == 91){
                    $ascii = 65;
                    $cv .= chr(strlen($cv)+65);
                }
            }
            $ascii = 65;
            $cv = '';
            $i++;
        } 

        $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
        ob_end_clean();
        header("Content-Type: application/vnd.ms-excel;");
        header("Content-Disposition:attachment;filename=5kcrm_user_".date('Y-m-d',mktime()).".xls");
        header("Pragma:no-cache");
        header("Expires:0");
        $objWriter->save('php://output'); 
    }
这里只粘贴了使用的代码,里面需要引用phpexcel,在上面搜索phpexcel就有很多下载的

再来一个简单的导出的方法:
public function oexcel()
    {
        header('Content-Type: application/vnd.ms-excel');
        header('Content-Disposition: attachment; filename=user.xls');
        header('Pragma: no-cache');
        header('Expires: 0');
        $title = array('手机', '昵称');
        $data = M('user')->field("login,uname")->select();
        echo iconv('utf-8', 'gbk', implode("\t", $title)), "\n";
        foreach ($data as $value) {
            echo iconv('utf-8', 'gbk', ' '.implode("\t", $value)), "\n";
        }

    }