You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Apps Script复制Google Sheets单元格内的图片至Google文档?

解决Google Sheets单元格内嵌图片复制到Google Docs的问题

你遇到的是**单元格内嵌图片(CellImage)**的获取问题——剪贴板粘贴到单元格的图片属于这类,和工作表上的浮动图片不同,getImages()只能抓取浮动图片,getDisplayValues()会直接忽略这类图片,只有getValue()能返回CellImage对象。

下面是修改后的代码,能完整复制带内嵌图片的表格到Google Docs:

function main(){
  const ss = SpreadsheetApp.getActiveSpreadsheet();
  const sheet = ss.getSheetByName("mysheet");
  const range = sheet.getDataRange();
  const numRows = range.getNumRows();
  const numCols = range.getNumColumns();

  const folder_id = "FOLDER_ID";
  const folder = DriveApp.getFolderById(folder_id);

  const doc = DocumentApp.create("KPI report");
  DriveApp.getFileById(doc.getId()).moveTo(folder);
  const body = doc.getBody();

  // 创建对应行列数的空表格
  const table = body.appendTable();
  table.setWidth(range.getWidth());

  for (let rowIdx = 0; rowIdx < numRows; rowIdx++) {
    const tableRow = table.appendTableRow();
    // 同步原表格行高
    tableRow.setHeight(range.getRowHeight(rowIdx + 1));

    for (let colIdx = 0; colIdx < numCols; colIdx++) {
      const cell = range.getCell(rowIdx + 1, colIdx + 1);
      const cellValue = cell.getValue();
      const tableCell = tableRow.appendTableCell();

      // 同步原表格列宽
      tableCell.setWidth(range.getColumnWidth(colIdx + 1));

      if (typeof cellValue === 'object' && cellValue.toString() === 'CellImage') {
        // 处理单元格内嵌图片
        const imageBlob = cellValue.getBlob();
        tableCell.appendImage(imageBlob);
        // 调整图片适应单元格大小(可选)
        const image = tableCell.getImages()[0];
        image.setWidth(tableCell.getWidth() - 10);
        image.setHeight(tableCell.getHeight() - 10);
      } else {
        // 处理普通文本内容
        tableCell.setText(cell.getDisplayValue());
      }
    }
  }
}

关键说明:

  • 不再用getDisplayValues()批量获取数据,而是逐个遍历单元格,判断是否为CellImage对象。
  • 通过cellValue.getBlob()提取图片的二进制数据,直接插入到Docs的对应单元格中。
  • 同步原表格的行高列宽,让Docs中的表格布局和原Sheet一致。
  • 可选的图片大小调整:避免图片撑破单元格,留出少量内边距。

注意事项:

  • 确保脚本有DriveApp和DocumentApp的权限,首次运行会弹出授权请求,直接授权即可。
  • 如果图片太大,可能需要调整行高列宽的同步逻辑,或者修改图片缩放比例。

内容的提问来源于stack exchange,提问作者Daniil

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.22 18:27:16