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

如何导出Google Sheets单个标签页的全部页面为PDF?

解决Google Sheets单标签页完整PDF导出问题

问题原因

你的代码中硬编码了固定的导出单元格范围参数:r1=0&c1=0&r2=27&c2=9,这个范围仅覆盖了标签页的第一页内容,导致PDF只导出了部分内容。

解决方案

直接移除URL中的固定范围参数(r1=、c1=、r2=、c2=相关片段),导出请求就会自动包含整个标签页的所有内容,自动处理分页逻辑,和GUI操作导出的效果完全一致。

修改后的完整代码:

function createPDF(ssId, sheet, pdfName, folder) {
  /**
   * Creates a PDF for the customer invoice template sheet
   * @param {string} ssId - Id of the Google Spreadsheet
   * @param {object} sheet - Sheet to be converted as PDF
   * @param {string} pdfName - File name of the PDF being created
   * @return {file object} PDF file as a blob
   */
  const url = "https://docs.google.com/spreadsheets/d/" + ssId + "/export" +
    "?format=pdf&" +
    "size=A4&" +
    'fitw=true&' +                        // fit to page width, false for actual size
    "fzr=true&" +
    "portrait=true&" +
    "fitw=true&" +
    "gridlines=false&" +
    "printtitle=false&" +
    "top_margin=0.5&" +
    "bottom_margin=0.25&" +
    "left_margin=0.5&" +
    "right_margin=0.5&" +
    "sheetnames=false&" +
    "pagenum=UNDEFINED&" +
    "attachment=true&" +
    "gid=" + sheet.getSheetId();

  const params = { method: "GET", headers: { "authorization": "Bearer " + ScriptApp.getOAuthToken() } };
  const blob = UrlFetchApp.fetch(url, params).getBlob().setName(pdfName)

  const pdfFile = folder.createFile(blob)
  return pdfFile
}

额外优化提示

如果后续需要导出特定动态范围(而非整个 sheet),不要硬编码行号列号,可通过sheet.getLastRow()和sheet.getLastColumn()获取当前 sheet 的有效内容边界,示例如下:

const fr = 0, fc = 0;
const lr = sheet.getLastRow();
const lc = sheet.getLastColumn();
// 在URL末尾追加范围参数
// "&r1=" + fr + "&c1=" + fc + "&r2=" + lr + "&c2=" + lc

这种方式能确保导出范围随sheet内容更新自动调整,避免因内容增减导致导出不完整。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.15 22:47:13