【发布时间】:2021-01-17 12:22:51
【问题描述】:
我编写了一个 php 脚本,它允许我读取上传的 excel 文件并插入文件夹中包含的所有图像,方法是使用单元格值“style”和“color”重命名它们以具有 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 = $sheet->getCell('H'.$row) ?: $stylecode;可以解决问题。 -
我刚刚用你的答案进行了测试,但它不起作用,每次跳过第二张照片时,它会将 style_color 放在第一张上并传递到下一个合并单元格而不拍摄第二张照片@ NigelRen
-
你试过
$sheet->getCell('H'.$row)->getValue() ?: $stylecode; -
是的,我刚刚将行改为 $stylecode = $sheet->getCell('H'.$row)->getValue() ?: $stylecode;而且效果很好!非常感谢您的帮助