将excel图片地址的内容追加到最后一列展示图片
将excel图片地址的内容追加到最后一列展示图片,如下效果:
try {
$rootDir = \Yii::getAlias('@app') . '/../uploads/excel';
$distRootDir = \Yii::getAlias('@app') . '/../uploads/out';
if (!file_exists($distRootDir)) {
1 mkdir($distRootDir);
}
$files = scandir($rootDir);
foreach ($files as $file) {
if ($file == '.' || $file == '..') {
continue;
}
$filePath = $rootDir . '/' . $file;
echo $filePath . PHP_EOL;
$newFilePath = $distRootDir . '/' . 'new_' . $file;
$objPHPExcel = \PhpOffice\PhpSpreadsheet\IOFactory::load($filePath);
$sheet = $objPHPExcel->getActiveSheet();
$highestRow = $sheet->getHighestRow(); // 获取总行数
$highestColumn = $sheet->getHighestColumn();
$nextColumn = \PhpOffice\PhpSpreadsheet\Cell\Coordinate::stringFromColumnIndex(\PhpOffice\PhpSpreadsheet\Cell\Coordinate::columnIndexFromString($highestColumn) + 1);
// 自动调整单元格大小以适应图片
$sheet->getColumnDimension($nextColumn)->setWidth(30); // 列宽(20大约等于150像素)
for ($row = 2; $row <= $highestRow; $row++) {
$sheet->getRowDimension($row)->setRowHeight(150); // 行高(75大约等于100像素)
$url = $sheet->getCell('E' . $row)->getValue(); // 获取E列对应行的单元格值
if (empty($url)) {
continue;
}
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT_MS, 2000);
$content = curl_exec($ch);
if ($content === false) {
echo $url . PHP_EOL;
$error = curl_error($ch);
echo "出现错误: " . $error . PHP_EOL;
continue;
}
curl_close($ch);
$tempImage = tempnam(sys_get_temp_dir(), 'excelImage') . '.jpg'; // 手动添加扩展名
$getContent = file_put_contents($tempImage, $content);
if (!file_exists($tempImage)) {
echo 'file: ' . $tempImage . '文件不存在' . PHP_EOL;
continue;
}
if ($getContent) {
$drawing = new \PhpOffice\PhpSpreadsheet\Worksheet\Drawing();
$drawing->setCoordinates($nextColumn . $row);
$drawing->setName($sheet->getCell('B' . $row)->getValue());
$drawing->setPath($tempImage);
$drawing->setWidth(200); // 调整图片宽度
$drawing->setHeight(200); // 调整图片高度
$drawing->setWorksheet($sheet);
}
// @unlink($tempImage);
}
// 保存修改后的Excel文件
$writer = IOFactory::createWriter($objPHPExcel, 'Xlsx');
$writer->save($newFilePath);
break;
}
$tmp = sys_get_temp_dir() . '/excelImage*';
$tmpFiles = glob($tmp);
foreach ($tmpFiles as $file) {
if (is_file($file)) {
unlink($file);
}
}
} catch (\Exception $e) {
echo $e->getMessage();
}