php Yii2 Excel导出图片资源到表格

php 复制代码
public static function exportSample($headers, $data, $fileName = 'excel', $writeType = 'Xls')
    {

        $img_field = ['sam_img','ref_img'];
        $_img_field_width = 16;
        $_img_field_height = 80;

        $excel = new Spreadsheet();
        $sheet = $excel->setActiveSheetIndex(0);

        // 设置标题单元格的样式:字体加粗,字体大小12,字体颜色红色,水平居中,垂直居中
        $styleArray = [
            'font' => [ //设置字体
                'bold' => true,
                'size' => 9,
//                'color' => array('rgb' => 'FF0000'),
            ],
            'alignment' => [ //对其方式
                'horizontal' => Excel::HORIZONTAL_CENTER, //居中
                'vertical' => Excel::VERTICAL_CENTER,
                'wrapText' => true, // 设置自动换行
            ],
            'fill'=>[ //设置表格的背景色
                'fillType' => Excel::FILL_SOLID,
                'startColor'=>['rgb' => 'B5C6EA'], //设备背景色
            ]
        ];

        $sheet->getStyle('A1:AC2')->applyFromArray($styleArray);

        $styleArray = [
            'borders' => [ //设备边框
                'outline' => [
                    'borderStyle' => Excel::BORDER_THIN, // 边框样式
                    'color' => ['rgb' => '000000'], // 边框颜色为黑色
                ],
            ],
            'alignment' => [ //对其方式
                'horizontal' => Excel::HORIZONTAL_CENTER, //居中
                'vertical' => Excel::VERTICAL_CENTER,
                'wrapText' => true, // 设置自动换行
            ],
        ];

        //循环两次-后面合并需要
        for ($i=1; $i<=2;$i++){
            // 设置标题
            $ordA = ord('A'); //65
            $key2 = ord("@"); //64
            foreach ($headers as $index => $title) {
                if ($ordA > ord("Z")) {
                    $colum = chr(ord("A")) . chr(++$key2); //超过26个字母 AA1,AB1,AC1,AD1...BA1,BB1...
                } else {
                    $colum = chr($ordA++);
                }
                $_p = $colum . $i;

                //写入标题并且设置样式
                $sheet->setCellValue($_p, $title)->getStyle($_p)->applyFromArray($styleArray);

                //图片单独处理宽度
                if(in_array($index,$img_field)){
                    $sheet->getColumnDimension($colum)->setWidth($_img_field_width);
                }
            }
        }

        //合并单元格-列-切重写
        $sheet->mergeCells('D1:M1')->setCellValue('D1', '计划产品性能参数');
        $sheet->mergeCells('N1:S1')->setCellValue('N1', '对标品牌产品性能参数');

        //合并单元格-行
        $h = ['A','B','C','T','U','V','W','X','Y','Z','AA','AB','AC'];
        foreach ($h as $k=>$y){
            $sheet->mergeCells($y.'1:'.$y.'2');
        }

        //图片地址
        $path = \Yii::getAlias('@excelImg');
        self::mkdirFile($path);

        $r = 3; //数据写入航标
        foreach ($data as $dKey => $log) {
            $column = 0;
            foreach ($headers as $kk => $vv) {
                $column++;

                $value = $log[$kk];
                if($kk == 'id'){
                    $value = $column;
                }

                if(in_array($kk,['sam_img','ref_img'])){

                    $_map = [
                        'sam_img'=>'L',
                        'ref_img'=>'M',
                    ];

                    $img_url = $log[$kk];
                    if(empty($img_url)){
                        continue;
                    }
                    $fileInfo = pathinfo($img_url);
                    $file =  $fileInfo['filename'] .'.'.$fileInfo['extension'];

                    $new_img_url = $path.'/'.$file;
                    //下载图片到本地
                    if (file_exists( $new_img_url) === false) {
                        $a = copy($img_url, $new_img_url);
                    }


                    if (file_exists($new_img_url)) {
                        $drawing = new Drawing();
                        $drawing->setPath($new_img_url);

                        $_rp = $_map[$kk].$r;
                        $drawing->setName('Image');
                        $drawing->setDescription('Image');
                        $drawing->setPath($new_img_url); // 设置图片路径
                        $drawing->setWidthAndHeight(80,80); // 设置图片宽度
                        $drawing->setCoordinates($_rp); // 指定单元格

                        // 设置图片格式选项,例如使其居中
                        $drawing->setResizeProportional(false); // 如果需要保持图片宽高比,设置为false

//                        $drawing->setOffsetX(5); // 设置横向偏移
//                        $drawing->setOffsetY(5); // 设置纵向偏移

                        $sheet->getRowDimension($r)->setRowHeight($_img_field_height);
                        $drawing->setWorksheet($sheet);
                    }

                }else {
                    $sheet->setCellValueExplicitByColumnAndRow($column, $r, $value, DataType::TYPE_STRING2);
                }
            }
            $r++;
        }
        $sheet->freezePane('A3'); //锁定行
        header('Content-Type: application/vnd.ms-excel');
        header('Content-Disposition: attachment;filename=' . $fileName . date('Y-m-d') . '.xls');
        header('Cache-Control: max-age=0');
        $excelWriter = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($excel, $writeType);
        $excelWriter->save('php://output');
        die();
    }


public static function mkdirFile($imageDir,$makeDir=1)
    {
        if (! file_exists($imageDir)) {
            if($makeDir){
                $a = mkdir($imageDir,0777,true);
            }else{
                echo '图片目录['.$imageDir.']不存在!';
                exit();
            }
        }
    }

表格效果

图片居中暂时还没找到非常好的实现方式,有经验的大佬欢迎指导

相关推荐
damoluomu6 小时前
挑 PHP CMS 之前,先学会看它的协议
php
小羊没烦恼!6 小时前
初探性能优化——2个月到4小时的性能提升
java·开发语言·windows·算法·c#
伞伞悦读7 小时前
【第38期】Python 模块与包详解:import、from、模块搜索路径、包结构和 __init__
开发语言·python
C语言小火车8 小时前
C/C++ 为什么需要编译器?
开发语言·c++
霍霍的袁9 小时前
【C++】map 和 set 的使用 | 从用法到底层
开发语言·c++·学习·visual studio
孙启超9 小时前
【AI开发之Rust】第 11 课:智能指针与内部可变性
开发语言·后端·rust
此生决int9 小时前
深入理解C++系列(20)——C++11(下)
开发语言·c++
CoderYanger11 小时前
A.每日一题:835. 图像重叠
java·开发语言·程序人生·leetcode·面试·职场和发展·学习方法
伞伞悦读12 小时前
【第37期】Python JSON 与配置详解:序列化、反序列化、嵌套结构和配置文件
开发语言·python·json
CCCCCCCCharlie12 小时前
Linux进程控制四大核心操作
linux·开发语言