我使用PHPSpreadsheet打开Excel工作表并在单元格A27中交换图像。 我的实际代码并不替换图像,而是将其添加为现有图像的叠加层:
$inputFileName = $_SERVER['DOCUMENT_ROOT']."output/test.xlsx";
$spreadsheet = $reader->load($inputFileName);
$sheet = $spreadsheet->getActiveSheet();
// Remove old image --> Fails
$sheet->setCellValue("A27", "");
echo "Bild ".$pfad_bild." in Zelle ".$zelle." einfügen<br>";
$image_placer = new \PhpOffice\PhpSpreadsheet\Worksheet\Drawing();
$image_placer->setName("myimg");
$image_placer->setDescription("myimg");
$image_placer->setPath("path/to/new/image");
$image_placer->setHeight(500);
$image_placer->setCoordinates('A27');
$image_placer->setOffsetX(0);
$image_placer->setOffsetY(0);
$image_placer->setWorksheet($spreadsheet->getActiveSheet());
// Save file with new tmp-name
$writer = new Xlsx($spreadsheet);
$writer->save($inputFileName."_");
// Delete old file
unlink($inputFileName);
// Rename new file to correct name
rename($inputFileName."_", $inputFileName);
有没有人知道如何从Cell中删除图像?
答案 0 :(得分:1)
这是答案,我实际上发现了:
global $reader;
$reader = IOFactory::createReader('Xlsx');
function exchange_image_within_cell($path_file,$cell,$path_img) {
global $reader;
$inputFileName = $_SERVER['DOCUMENT_ROOT'].$path_file;
$spreadsheet = $reader->load($inputFileName);
$bilder_array=$spreadsheet->getActiveSheet()->getDrawingCollection();
$bilder_array_copy = $bilder_array->getArrayCopy();
$i = 0;
foreach ($bilder_array_copy as $drawing) {
$coordinates=$drawing->getCoordinates();
if ($coordinates==$cell) {
// Delete Image from Array/Cell
unset($bilder_array_copy[$i]);
}
$i++;
}
// Reorder and exchange array
$bilder_array_copy = array_values($bilder_array_copy);
$bilder_array->exchangeArray($bilder_array_copy);
$sheet = $spreadsheet->getActiveSheet();
// Place new image
$sheet->setCellValue($cell, "");
$image_placer = new \PhpOffice\PhpSpreadsheet\Worksheet\Drawing();
$image_placer->setName($path_img);
$image_placer->setDescription($path_img);
$image_placer->setPath($path_img);
$image_placer->setHeight(500);
$image_placer->setCoordinates(''.$cell.'');
$image_placer->setOffsetX(0);
$image_placer->setOffsetY(0);
$image_placer->setWorksheet($spreadsheet->getActiveSheet());
// Save file with new tmp-name;
$writer = new Xlsx($spreadsheet);
$writer->save($inputFileName."_");
// Delete old file
unlink($inputFileName);
// Rename new file
rename($inputFileName."_", $inputFileName);
}
答案 1 :(得分:0)
Daniel的回答是正确的,但一点也不简短。基本上,一旦知道要从工作表$i
中删除的图形索引$sheet
,就可以使用:
$drawings = $sheet->getDrawingCollection();
unset($drawings[$i]);