如何在 php 中跳过 Excel 文件的几行?

How to skip several lines of an Excel file in php?

我有一个包含多张图片的 Excel 文件 (xlsx)

而且我有这个 php 脚本,它允许我提取其中包含的照片,将它们插入文件夹中并根据每张照片前面的单元格名称重命名它们。 该脚本有效,但我想从第 5 行开始阅读。我尝试使用 $i <= 3 跳过前 4 行,但这会导致图片名称发生变化。我该如何解决我的问题?

<?php

require_once 'PHPExcel/Classes/PHPExcel/IOFactory.php';
$path = 'C:/wamp64/www/Extract_pictures_Excel/imagetest.xlsx';
$objPHPExcel = PHPExcel_IOFactory::load($path);

$i = 0;

foreach ($objPHPExcel->getActiveSheet()->getDrawingCollection() as $drawing ) {
    $i++;
  

    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/images/';
     
    }

    $sheet = $objPHPExcel->getActiveSheet();
    foreach ($sheet->getDrawingCollection() as $drawing) {
    $row = (int)substr($drawing->getCoordinates(), 1);

  // retrieve the image data anyway you like

    $stylecode = $sheet->getCell('B'.$row)->getValue();
    $colorcode = $sheet->getCell('C'.$row)->getValue();
    $finalname = $stylecode.'_'.$colorcode;
    $myFileName = $chemin.$finalname.'.'.$extension;
    file_put_contents($myFileName,$imageContents);
 
  }
}
 ?>

我认为getDrawingCollection()给你一个列表,列出了活动sheet上的所有绘图,但这个列表与单元格坐标没有直接关系。因此,跳过此列表的某些项目与跳过行不同

不确定旧的 PHPExcel 库如何,但对于当前的 PhpOffice\PhpSpreadsheet,Drawing or BaseDrawing objects should have their $coordinates 属性.

示例:

$sheet = $objPHPExcel->getActiveSheet();
foreach ($sheet->getDrawingCollection() as $drawing) {
  $row = (int)substr($drawing->getCoordinates(), 1);

  // retrieve the image data anyway you like

  $stylecode = $sheet->getCell('B'.$row)->getValue();
  $colorcode = $sheet->getCell('C'.$row)->getValue();
  $finalname = $stylecode.'_'.$colorcode;

  ...
}

您应该解析 $drawing->coordinates 以检索其相邻单元格的值。