如何用Google Apps Script将合并单元格中的图片复制到单个单元格?
合并单元格图片复制到单个单元格的解决方案
直接使用copyTo()或moveTo()会保留图片原始尺寸,导致图片跨多个单元格。需要单独提取浮动图片并调整尺寸适配目标单元格,代码实现如下:
function copyImageToSingleCell() { const sourceSheet = SpreadsheetApp.getActive().getSheetByName('Source'); const destinationSheet = SpreadsheetApp.getActive().getSheetByName('Destination'); // 指定源合并单元格区域和目标单元格 const sourceRange = sourceSheet.getRange('B6:B16'); const targetRange = destinationSheet.getRange('B1'); // 筛选出源区域内的目标图片 const images = sourceSheet.getImages(); const targetImage = images.find(img => { const imgAnchor = img.getAnchorCell(); return sourceRange.getRow() <= imgAnchor.getRow() && imgAnchor.getRow() <= sourceRange.getLastRow() && imgAnchor.getColumn() === sourceRange.getColumn(); }); if (!targetImage) return; // 未找到图片时终止 // 获取目标单元格的尺寸信息 const targetAnchor = destinationSheet.getRange(targetRange.getRow(), targetRange.getColumn()); const cellWidth = targetRange.getWidth(); const cellHeight = targetRange.getHeight(); // 复制图片到目标工作表并调整适配单元格 const copiedImg = targetImage.copyTo(destinationSheet); copiedImg.setAnchorCell(targetAnchor); copiedImg.setWidth(cellWidth); copiedImg.setHeight(cellHeight); // 若需移动图片而非复制,取消下方注释 // targetImage.remove(); }
关键说明:
- 浮动图片需要通过
getImages()遍历筛选,判断其锚点单元格是否在源合并区域内 - 通过
setWidth()和setHeight()将图片尺寸调整为目标单元格的大小 setAnchorCell()确保图片锚定到目标单元格,避免位置偏移
内容的提问来源于stack exchange,提问作者Pat
相关产品推荐
相关产品推荐

