簡體   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