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

如何用Google Apps Script在Google Sheets中实现无多偏好设置的快速打印?

Google Sheets 一键固定偏好打印方案

实现思路

通过Google Apps Script创建自定义菜单,结合客户端CSS媒体查询预设打印样式,点击菜单即可触发带有固定偏好的打印窗口,省去重复设置操作。

代码实现

打开目标Google Sheets,点击「扩展程序」>「Apps Script」,替换默认代码为以下内容:

// 打开表格时生成自定义菜单
function onOpen() {
  SpreadsheetApp.getUi()
    .createMenu('一键打印')
    .addItem('按预设设置打印', 'printWithSettings')
    .addToUi();
}

// 触发带固定偏好的打印流程
function printWithSettings() {
  // 可选:设置指定打印区域(参数:行起始, 列起始, 行数, 列数)
  const sheet = SpreadsheetApp.getActiveSheet();
  sheet.setPrintArea(1, 1, 20, 6); // 示例:打印A1-F20区域

  const printHtml = HtmlService.createHtmlOutput(`
    <script>
      window.onload = () => {
        window.print();
        google.script.host.close();
      }
    </script>
    <style>
      @media print {
        @page {
          margin: 1cm; /* 自定义页边距 */
          size: A4 portrait; /* 纸张规格:A4 纵向 */
        }
        /* 确保打印颜色与屏幕一致 */
        * {
          print-color-adjust: exact;
        }
        /* 隐藏表格顶部工具栏,只打印内容 */
        #docs-editor-container > div:first-child {
          display: none !important;
        }
      }
    </style>
  `).setWidth(10).setHeight(10);

  SpreadsheetApp.getUi().showModalDialog(printHtml, '准备打印');
}

自定义调整

根据需求修改以下内容:

  • 打印区域:调整setPrintArea的四个参数,对应工作表的行、列范围
  • 打印样式:在@media print区块内修改:
    • 纸张大小:替换为A3/letter等规格
    • 打印方向:将portrait改为landscape(横向)
    • 页边距:修改margin数值,比如0.5cm
    • 其他规则:可添加隐藏特定单元格、调整字体样式等代码

使用方法

  1. 保存脚本项目,回到表格页面刷新
  2. 顶部菜单栏会出现「一键打印」选项
  3. 点击「按预设设置打印」,浏览器弹出打印窗口,确认预设参数后即可打印

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 12:42:28