PHP获取excel表格里面的图片

先安装插件包

composer require phpoffice/phpspreadsheet

获取excel中的图片并保存(我用的是TP5.1)

//加载打开文件 $file
$reader = \PhpOffice\PhpSpreadsheet\IOFactory::createReader('Xlsx');
//这一行不要写,写了这个是获取不到图片这些数据的
//$reader->setReadDataOnly(TRUE);
$spreadsheet = $reader->load($file);
$objWorksheet = $spreadsheet->getSheet(0);
$data = $objWorksheet->toArray();

//遍历
foreach ($objWorksheet->getDrawingCollection() as $drawing) {
    list($startColumn, $startRow) = Coordinate::coordinateFromString($drawing->getCoordinates());
    $imageFileName = $drawing->getCoordinates() . mt_rand(1000, 9999);

    switch ($drawing->getExtension()) {
        case 'jpg':
        case 'jpeg':
            //加了时间戳是为了不让文件名重复
            $imageFileName .= '_'.time().'.jpg';
            $source = imagecreatefromjpeg($drawing->getPath());
            imagejpeg($source, $imageFilePath . $imageFileName);
            break;
        case 'gif':
            $imageFileName .= '_'.time().'.gif';
            $source = imagecreatefromgif($drawing->getPath());
            imagegif($source, $imageFilePath . $imageFileName);
            break;
        case 'png':
            $imageFileName .= '_'.time().'.png';
            $source = imagecreatefrompng($drawing->getPath());
            imagepng($source, $imageFilePath. $imageFileName);
            break;
    }
    $startColumn = ABC2decimal($startColumn);
    //把保存成链接的文件放回拿到的数据中
    $data[$startRow-1][$startColumn] = $this->request->domain() . $path . $imageFileName;
}

ABC2decimal方法

function ABC2decimal($abc)
{
    $ten = 0;
    $len = strlen($abc);
    for($i=1;$i<=$len;$i++){
        $char = substr($abc,0-$i,1);//反向获取单个字符

        $int = ord($char);
        $ten += ($int-65)*pow(26,$i-1);
    }
    return $ten;
}

看不懂没关系,我也是抄过来用的

Posted in PHP