如何用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 - 其他规则:可添加隐藏特定单元格、调整字体样式等代码
- 纸张大小:替换为
使用方法
- 保存脚本项目,回到表格页面刷新
- 顶部菜单栏会出现「一键打印」选项
- 点击「按预设设置打印」,浏览器弹出打印窗口,确认预设参数后即可打印
内容的提问来源于stack exchange,提问作者Le Canh
相关产品推荐
相关产品推荐

