>  기사  >  백엔드 개발  >  PHP를 사용하여 Excel에서 그림을 읽는 방법(코드 포함)

PHP를 사용하여 Excel에서 그림을 읽는 방법(코드 포함)

angryTom
angryTom앞으로
2019-11-28 14:57:105355검색

PHP를 사용하여 Excel에서 그림을 읽는 방법(코드 포함)

오늘 Excel에서 사진을 읽어 달라는 요청을 받았습니다. 인터넷에서 몇 가지 정보를 검색하고 기본적으로 내 요구 사항을 깨달았습니다. 그러나 일부 코드로 인해 A를 발견했습니다. 오래 전에 일부 라이브러리 메서드가 제거되어 더 이상 존재하지 않으므로 자신의 프로젝트에 직접 이식할 수 없으며 약간 수정해야 합니다.

(추천 학습: PHP 동영상 튜토리얼)

여기서 phpspreadsheet 및 PHPExcel 확장 사용을 소개합니다. Excel에서 그림을 읽는 기능을 각각 구현하려면:

PHP를 사용하여 Excel에서 그림을 읽는 방법(코드 포함)

PHPSreadsheet

First phpspreadsheet를 설치하세요. 온라인 서버 PHP 버전은 PHP5.6이므로 PHP5.6과 호환되는 버전을 설치해야 합니다.

composer require phpoffice/phpspreadsheet=1.8.2

에서 버전 1.8.2를 설치한 다음 프로젝트에서 사용할 수 있습니다.

use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\IOFactory;

$imageFilePath = './uploads/imgs/'; //图片本地存储的路径
if (!file_exists($imageFilePath)) { //如果目录不存在则递归创建
    mkdir($imageFilePath, 0777, true);
}

try {
    $inputFileName = './files/1.xlsx';  //包含图片的Excel文件
    $objRead = IOFactory::createReader('Xlsx');
    $objSpreadsheet = $objRead->load($inputFileName);
    $objWorksheet = $objSpreadsheet->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 .= '.jpg';
                $source = imagecreatefromjpeg($drawing->getPath());
                imagejpeg($source, $imageFilePath . $imageFileName);
                break;
            case 'gif':
                $imageFileName .= '.gif';
                $source = imagecreatefromgif($drawing->getPath());
                imagegif($source, $imageFilePath . $imageFileName);
                break;
            case 'png':
                $imageFileName .= '.png';
                $source = imagecreatefrompng($drawing->getPath());
                imagepng($source, $imageFilePath, $imageFileName);
                break;
        }
        $startColumn = ABC2decimal($startColumn);
        $data[$startRow-1][$startColumn] = $imageFilePath . $imageFileName;
    }
    dump($data);die();
} catch (\Exception $e) {
    throw $e;
}

public 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;
}

이미지를 읽어서 로컬 서버에 저장한 것을 볼 수 있습니다

PHP를 사용하여 Excel에서 그림을 읽는 방법(코드 포함)

PHPExcel#🎜 🎜#

PHPExcel의 Excel 파일 내용 읽는 방법은 phpspreadsheet와 거의 동일합니다. 하지만, phpspreadsheet는 PHPExcel을 기반으로 작성되었으므로 사용을 권장합니다. phpspreadsheet를 먼저 사용했다면, PHPExcel 없이도 PHPExcel을 계속 사용할 수 있습니다.

use PHPExcel_IOFactory;
use PHPExcel_Cell;

try {
    $inputFileName = &#39;./files/1.xlsx&#39;;
    $inputFileType = PHPExcel_IOFactory::identify($inputFileName);
    $objReader = PHPExcel_IOFactory::createReader($inputFileType);
    $objPHPExcel = $objReader->load($inputFileName);
} catch (\Exception $e) {
    die(&#39;加载文件发生错误:"&#39;.pathinfo($inputFileName,PATHINFO_BASENAME).&#39;": &#39;.$e->getMessage());
}

$sheet = $objPHPExcel->getSheet(0);
$data = $sheet->toArray(); //该方法读取不到图片,图片需单独处理
$imageFilePath = &#39;./uploads/imgs/&#39;; //图片本地存储的路径
if (!file_exists($imageFilePath)) {
    mkdir($imageFilePath, 0777, true);
}

//处理图片
foreach ($sheet->getDrawingCollection() as $img) {
    list($startColumn, $startRow) = PHPExcel_Cell::coordinateFromString($img->getCoordinates()); //获取图片所在行和列
    $imageFileName = $img->getCoordinates() . mt_rand(1000, 9999);
    switch($img->getExtension()) {
        case &#39;jpg&#39;:
        case &#39;jpeg&#39;:
            $imageFileName .= &#39;.jpeg&#39;;
            $source = imagecreatefromjpeg($img->getPath());
            imagejpeg($source, $imageFilePath.$imageFileName);
            break;
        case &#39;gif&#39;:
            $imageFileName .= &#39;.gif&#39;;
            $source = imagecreatefromgif($img->getPath());
            imagejpeg($source, $imageFilePath.$imageFileName);
            break;
        case &#39;png&#39;:
            $imageFileName .= &#39;.png&#39;;
            $source = imagecreatefrompng($img->getPath());
            imagejpeg($source, $imageFilePath.$imageFileName);
            break;
    }
    $startColumn = ABC2decimal($startColumn);
    $data[$startRow-1][$startColumn] = $imageFilePath . $imageFileName;

}
var_dump($data);

public 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;
}

이 기사는 PHP 중국어 웹사이트,

phpquestion 열에서 가져온 것입니다. 학습에 오신 것을 환영합니다!

위 내용은 PHP를 사용하여 Excel에서 그림을 읽는 방법(코드 포함)의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
이 기사는 cnblogs.com에서 복제됩니다. 침해가 있는 경우 admin@php.cn으로 문의하시기 바랍니다. 삭제