导出PDF,我可以提供两个范围吗?

时间:2020-10-09 16:25:30

标签: google-apps-script google-sheets

我正在使用此代码将工作表导出为PDF。

{var url_ext = '/export?exportFormat=pdf&format=pdf'  
      
      + (sheetId ? ('&gid=' + sheetId) : ('&id=' + spreadsheetId))
      + (shRng ? ('&range=A1:L43') : null)
      // following parameters are optional...
      + '&size=A4'      // paper size
      + '&portrait=true'    // orientation, false for landscape
      + '&fitw = true' // fit to width, false for actual size
      + '&sheetnames=false&printtitle=false&pagenumbers=false'  //hide optional headers and footers
      + '&gridlines=false'  // hide gridlines
      + '&fzr=false';       // do not repeat row headers (frozen rows) on each page
      }

是否可以提供两个范围并将它们导出为相同的PDF但在不同页面上? Invoice

这样做的原因是我希望发送图像中显示的整个电子表格,但是我希望M-Z列显示在其他页面上。现在,我可以给出1个范围(A1:L43),并且可以正常打印。

或者,也许有一种方法可以插入分页符,在导出之前更改表的比例。将表格分为同一个人推荐的两页PDF的另一种方式。

1 个答案:

答案 0 :(得分:2)

如果我对您的理解正确,那么您希望将不同范围从某个表导出到PDF文件(每个范围中的数据应位于不同的页面)。

如果是这种情况,并且假设范围在活动工作表中,则可以执行以下操作:

代码示例:

// Copyright 2020 Google LLC.
// SPDX-License-Identifier: Apache-2.0

function MULTIPLE_RANGES_TO_PDF() {
  const ss = SpreadsheetApp.getActive();
  const tempSS = SpreadsheetApp.create("Temporary Spreadsheet");
  const sourceSheet = ss.getActiveSheet();
  const rangeNotations = ["A1:L43", "M1:Z43"];
  rangeNotations.forEach(rangeNotation => {
    const sourceRange = sourceSheet.getRange(rangeNotation);
    const tempSheet = ss.insertSheet();
    sourceRange.copyTo(tempSheet.getRange("A1"));
    tempSheet.copyTo(tempSS);
    ss.deleteSheet(tempSheet);
  });
  tempSS.deleteSheet(tempSS.getSheets()[0]); // Remove first sheet in temp (blank)
  var url = "https://www.googleapis.com/drive/v3/files/" + tempSS.getId() + "/export?mimeType=application/pdf";
  var params = {
    headers: { "Authorization": "Bearer " + ScriptApp.getOAuthToken() }
  }
  var pdf = UrlFetchApp.fetch(url, params).getBlob();
  DriveApp.createFile(pdf).setName("My exported PDF.pdf");
  Drive.Files.remove(tempSS.getId());
}