1. 程式人生 > >TP3.2與PHPExcel結合的例子

TP3.2與PHPExcel結合的例子

function getUserData($res){

        $xlsName  = "User";
        $xlsCell  = array(
            array('user_id','使用者id'),
            array('data_value','圖片'),
        );
        $xlsModel = M('visa_data');
        $xlsData  = $xlsModel->Field('user_id,data_value')->where('vd_id = 12485')->select();
        $this->exportExcel($xlsName,$xlsCell,$xlsData);  
    }

    function exportExcel($expTitle,$expCellName,$expTableData){
        $xlsTitle = iconv('utf-8', 'gb2312', $expTitle);//檔名稱
        $fileName = $expTitle.date('_YmdHis');//or $xlsTitle 檔名稱可根據自己情況設定
        $cellNum = count($expCellName);
        $dataNum = count($expTableData);
        vendor("PHPExcel.PHPExcel");
        $objPHPExcel = new \PHPExcel();
       $objActSheet=$objPHPExcel->getActiveSheet();
        $objActSheet->getDefaultRowDimension()->setRowHeight(200);//設定預設高度wps不好使
        $cellName = array('A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','AA','AB','AC','AD','AE','AF','AG','AH','AI','AJ','AK','AL','AM','AN','AO','AP','AQ','AR','AS','AT','AU','AV','AW','AX','AY','AZ');
        $objPHPExcel->getActiveSheet(0)->mergeCells('A1:'.$cellName[$cellNum-1].'1');//合併單元格
        $objPHPExcel->setActiveSheetIndex(0)->setCellValue('A1', $expTitle.'  Export time:'.date('Y-m-d H:i:s'));
        for($i=0;$i<$cellNum;$i++){
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue($cellName[$i].'2', $expCellName[$i][1]);
        }
        $img_type = array('jpg','png','jpeg','gif');
        // Miscellaneous glyphs, UTF-8
        for($i=0;$i<$dataNum;$i++){
            for($j=0;$j<$cellNum;$j++){
            $objActSheet->getColumnDimension($cellName[$j])->setWidth(30); //行寬
            $value = $expTableData[$i][$expCellName[$j][0]];
            $ext = pathinfo($value)['extension'];
            // echo $ext;
                if(in_array($ext,$img_type)){
                    $objDrawing[$j] = new \PHPExcel_Worksheet_Drawing();
                    $objDrawing[$j]->setPath('./Soxzg/Uploads/images/'.$value);
                    $objDrawing[$j]->setHeight('70px'); //照片高度
                    $objDrawing[$j]->setWidth('70px'); //照片寬度
                    $objDrawing[$j]->setCoordinates($cellName[$j].($i+3));
                    $objDrawing[$j]->setWorksheet($objActSheet);
                }else{
                    $objPHPExcel->getActiveSheet(0)->setCellValue($cellName[$j].($i+3), $expTableData[$i][$expCellName[$j][0]]);
                }
            }
        }

 
       $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
        // $objWriter->save('php://output');
        $objWriter = new \PHPExcel_Writer_Excel2007($objPHPExcel);
        $res = $objWriter->save("./data/".$fileName.'.xls');

    }