繁体   English   中英

如何在php中读取带有合并单元格的excel文件?

[英]How to read a excel file with merged cells in php?

我编写了一个 php 脚本,它允许我读取上传的 excel 文件,并通过使用单元格值“样式”和“颜色”将它们重命名为 style_color.jpg 来插入文件夹中包含的所有图像。 该脚本工作正常,但如果我上传包含合并单元格的 xlsx 文件,如下所示:

在此处输入图片说明

具有相同“样式”的图像不起作用。该工具只会将样式放在第一张图像上。 我想调用前两个图像:

SCJEG4_1041
SCJEG4_0049

如何读取这些合并的单元格?

<?php

//uploaded xlsx file recovery
$xlsx="C:/wamp64/www/Extract_pictures_Excel/xlsx_files/".date('Y_m_d H-i-s')."_images.xlsx";
move_uploaded_file($_FILES["mon_fichier"]["tmp_name"],$xlsx);

require_once 'PHPExcel/Classes/PHPExcel/IOFactory.php';
$objPHPExcel = PHPExcel_IOFactory::load($xlsx);

//Unique name folder for the pictures
$dirname = uniqid();
mkdir("C:/wamp64/www/Extract_pictures_Excel/pictures_folders/$dirname/");

//reading the xlsx file
$sheet = $objPHPExcel->getActiveSheet();
foreach ($sheet->getDrawingCollection() as $drawing ) {
    
    if ($drawing instanceof PHPExcel_Worksheet_MemoryDrawing) {
        ob_start();
        call_user_func(
            $drawing->getRenderingFunction(),
            $drawing->getImageResource()
        );
        $imageContents = ob_get_contents();
        ob_end_clean();
        switch ($drawing->getMimeType()) {
            case PHPExcel_Worksheet_MemoryDrawing::MIMETYPE_PNG :
                $extension = 'png'; break;
            case PHPExcel_Worksheet_MemoryDrawing::MIMETYPE_GIF:
                $extension = 'gif'; break;
            case PHPExcel_Worksheet_MemoryDrawing::MIMETYPE_JPEG :
                $extension = 'jpg'; break;
        }
    } else {
        $zipReader = fopen($drawing->getPath(),'r');
        $imageContents = '';
        while (!feof($zipReader)) {
            $imageContents .= fread($zipReader,1024);
        }
        fclose($zipReader);
        $extension = $drawing->getExtension();
        $chemin = "C:/wamp64/www/Extract_pictures_Excel/pictures_folders/$dirname/";
    }    
    
    //retrieving cell values for the images name
    $row = (int) substr($drawing->getCoordinates(), 1);        
    $stylecode = $sheet->getCell('H'.$row)->getValue();
    $colorcode = $sheet->getCell('E'.$row)->getValue();
    $finalname = $stylecode.'_'.$colorcode;
    $myFileName = $chemin.$finalname.'.'.$extension;
    file_put_contents($myFileName, $imageContents); 
}

?>

如果您可以假设您按顺序读取行,则可以获得单元格值,如果单元格为空,则使用前一个值。 此代码使用?:表示如果它是空白的,请使用$stylecode ...

$stylecode = $sheet->getCell('H'.$row)->getValue() ?: $stylecode;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM