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();
            }
        }
    }

表格效果

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

相关推荐
不听话坏2 小时前
Ignition篇(下 一) 动态执行前的事情
开发语言·前端·javascript
likeyi072 小时前
require 和 import的区别
开发语言·前端
远离UE43 小时前
UE5 compute shader 原子加
开发语言·c++·ue5
C+-C资深大佬3 小时前
C++ 显式类型转换详解:static_cast、dynamic_cast、const_cast、reinterpret_cast
开发语言·c++
KaMeidebaby4 小时前
卡梅德生物技术快报|抗体亲和力成熟工业化调控新机制:差异性浆细胞增殖工艺优化思路
java·开发语言·人工智能·算法·机器学习·架构·spark
luj_17684 小时前
心形曲线轨迹控制三大关键技术
c语言·开发语言·c++·经验分享·算法
Mininglamp_27185 小时前
Claude Code 封禁中国开发者之后:本地 AI 编程工具的替代方案实测
开发语言·人工智能·windows·开源软件·ai-native
思麟呀5 小时前
C++17(三)if constexpr+折叠表达式
开发语言·c++
醉城夜风~5 小时前
Java详解经典算法题:接雨水(三种实现方案+原理剖析)
java·开发语言·算法
qydz115 小时前
杰理开发基础知识(3)
开发语言·嵌入式开发·杰理科技