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

如何用Google Apps Script切换调整Google Sheets矩形绘图宽度

解决方案:切换Google Sheets绘图宽度

问题根源

你的初始代码报错是因为getDrawings()返回的是绘图对象数组,而非单个绘图实例,所以不能直接对数组调用setWidth()方法。需要先从数组中取出目标绘图对象(因为你说工作表仅有一个绘图,直接取第一个元素即可)。

完整实现代码

function toggleDrawingWidth() {
  // 获取当前活动工作表
  const activeSheet = SpreadsheetApp.getActiveSheet();
  // 获取工作表中的所有绘图(返回数组)
  const drawings = activeSheet.getDrawings();
  // 取第一个绘图对象(目标工作表仅一个绘图)
  const targetDrawing = drawings[0];

  // 定义宽/窄两种宽度值
  const narrowWidth = 94;
  const wideWidth = 1242;

  // 获取当前绘图宽度,判断后切换目标宽度
  const currentWidth = targetDrawing.getWidth();
  const newWidth = currentWidth === wideWidth ? narrowWidth : wideWidth;

  // 设置新宽度,高度和左上角位置会自动保留
  targetDrawing.setWidth(newWidth);
}

关键说明

  • 切换逻辑:通过判断当前宽度,实现宽→窄、窄→宽的双向切换
  • 属性保留:调用setWidth()仅修改宽度,绘图的高度、左上角坐标等原有属性不会被改动,完全符合你的需求
  • 适配性:因为明确目标工作表只有一个绘图,所以直接取drawings[0],如果后续有多个绘图,可通过drawings.find()等方法匹配特定绘图(比如按名称)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 03:10:55