隐藏工作表会导致Google表格的Export-sheet-as-PDF URL的输出损坏 [英] Hidden sheet results in corrupted output of the export-sheet-as-PDF URL of Google Sheets

查看:72
本文介绍了隐藏工作表会导致Google表格的Export-sheet-as-PDF URL的输出损坏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个脚本来生成一些PDF,将它们保存到驱动器中,并在需要时通过电子邮件发送给他们.

I created a script to generate some PDFs, save them to drive and email them if this was required.

该脚本可以正常工作,但有一个问题除外:当我隐藏名为"TrafficAgentPDF"的工作表并运行脚本时,它会在云端硬盘中创建PDF,但是由于某种原因它已损坏.不能由谷歌打开;在浏览器中打开时为空白.取消隐藏工作表,一切正常.

The script works fine, except for one issue: When I hide the sheet called "TrafficAgentPDF" and run my script, it creates the PDF in Drive, but it's corrupted somehow. Cannot be opened by google; when opening it in a browser, it's blank. Unhide the sheet, and it all works.

TrafficAgentPDF工作表在另一个工作表上执行vlookup,以显示图像而不是值.图像是小图标,仅使用了3个.红色交通灯,琥珀色交通灯和绿色. (我想提一下,以防万一这是一个奇怪的渲染问题.)

The TrafficAgentPDF sheet does a vlookup on another sheet, to show images instead of values. The images are small icons, and only 3 are used. A red traffic light, amber traffic light and green. (Thought I'd mention that in case it was a weird rendering issue.)

这是我的剧本.如果有任何不清楚的地方,请告诉我,我会对其进行注释.

Here is my script. If anything is unclear, let me know and I will annotate it.

function getAgentName() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  ss.getRangeByName('Header').clearContent();
  ss.getRangeByName('Scores').clearContent();
  ss.getRangeByName('Comments').clearContent();
  var sheet = ss.getSheetByName("PDF Creator");
  var range = sheet.getRange("A2")
  var value = range.getValue();

  if(value != 0)
    getAgentData(value);
  else
    Browser.msgBox("You need to go to the sheet named PDF Creator and put an agent name in cell A2");
}

function getAgentData(value){
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sourceSheet = ss.getSheetByName("Form responses 1")
  var sourceRange = sourceSheet.getRange(2, 1, sourceSheet.getLastRow(), sourceSheet.getLastColumn());
  var sourceValues = sourceRange.getValues();
  sourceValues.sort(function(a, b) { return b[0] - a[0] });

  var agentData = [];
  var commentsData = [];
  for(i = 0; i < sourceValues.length; i++) {
    // Defines the data layout for PDF.
    var agentName = sourceValues[i][2];
    var dateTime = sourceValues[i][3];
    var callType = sourceValues[i][7];
    var opening = sourceValues[i][8];
    var rootCause = sourceValues[i][9];
    var rootFix = sourceValues[i][10];
    var process = sourceValues[i][11];
    var consumer = sourceValues[i][12];
    var control = sourceValues[i][13];
    var wrapup = sourceValues[i][14];
    var dpa = sourceValues[i][15];
    var score = sourceValues[i][22];
    var comments = sourceValues[i][16];

    var agentRow = [dateTime, callType, opening, rootCause, rootFix, process, consumer, control, wrapup, dpa, score];
    var commentsRow = [dateTime, comments];

    if(agentName == value && agentData.length < 9) {
      agentData.push(agentRow)
      commentsData.push(commentsRow)
    }
  }
  agentData.sort(   function(a, b) { return b[0] - a[0]; });
  commentsData.sort(function(a, b) { return b[0] - a[0]; });

  var destSheet = ss.getSheetByName("AgentPDF");
  destSheet.getRange("A1").setValue(value + "'s Quality Score card");
  destSheet.getRange(6, 1, agentData.length, agentData[0].length).setValues(agentData);

  destSheet.getRange(18, 1, commentsData.length, commentsData[0].length).setValues(commentsData);

  SpreadsheetApp.flush();
  emailSpreadsheetAsPDF();
}

function emailSpreadsheetAsPDF() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getSheetByName("PDF Creator");
  var now = new Date().toString();
  var weekCommencing = sheet.getRange("C1").getValue();
  var coachEmail = sheet.getRange("C4").getValue();
  var coachName = sheet.getRange("A4").getValue();
  var agentName = sheet.getRange("A2").getValue();
  var agentEmail = sheet.getRange("C2").getValue();
  var sendEmail = sheet.getRange("A6").getValue();

  var subject = "Quality Scorecard for - " + agentName + " created on: " + now;

  var monthNames = [
    "Jan", "Feb", "Mar",
    "Apr", "May", "Jun", "Jul",
    "Aug", "Sep", "Oct",
    "Nov", "Dec"
  ];

  var day = weekCommencing.getDate();
  var monthIndex = weekCommencing.getMonth();
  var year = weekCommencing.getFullYear();

  var clean = day + ' ' + monthNames[monthIndex] + ' ' + year;

  var bodyCoach = "Hello " + coachName + ". Please find attached "+ agentName + "'s quality scorecard." + " Week commencing " + clean;
  var bodyAgent = "Hello " + agentName + ". Please find attached your  quality scorecard." + " Week commencing " + clean;

  /** Specify PDF export parameters
   * // From: https://code.google.com/p/google-apps-script-issues/issues/detail?id=3579
   * exportFormat = pdf / csv / xls / xlsx
   * gridlines = true / false
   * printtitle = true (1) / false (0)
   * size = legal / letter/ A4
   * fzr (repeat frozen rows) = true / false
   * portrait = true (1) / false (0)
   * fitw (fit to page width) = true (1) / false (0)
   * add gid if to export a particular sheet - 0, 1, 2,..
   */
  var url = ss.getUrl().replace(/edit$/,'');
  var url_ext = 'export?exportFormat=pdf&format=pdf'   // export as pdf
        + '&size=a4'                           // paper size
        + '&portrait=1'                        // orientation, false for landscape
        + '&fitw=true&source=labnol'           // fit to width, false for actual size
        + '&sheetnames=false&printtitle=false' // hide optional headers and footers
        + '&pagenumbers=false&gridlines=false' // hide page numbers and gridlines
        + '&fzr=false'                         // do not repeat row headers (frozen rows) on each page
        + '&gid=1809314965';                   // the sheet's ID
  var response = UrlFetchApp.fetch(url + url_ext , {
      headers: {
        'Authorization': 'Bearer ' + ScriptApp.getOAuthToken()
      }
  });

  var file = response.getBlob().setName(agentName +"'s Quality Score Card Week Commencing: " + clean + '.pdf');
  writeFiles(file, clean);

  if (coachEmail != "no email"){
    GmailApp.sendEmail(coachEmail, subject, bodyCoach, {attachments:[file]});
  }

  if(sendEmail == "Yes"){
    GmailApp.sendEmail(agentEmail, subject, bodyAgent, {attachments:[file]});
  }

  ss.getRangeByName('Header').clearContent();
  ss.getRangeByName('Scores').clearContent();
  ss.getRangeByName('Comments').clearContent();
  ss.getRangeByName('AgentName').clearContent();
  ss.getRangeByName('Coach').clearContent();
  ss.getRangeByName('SendEmail').clearContent();
}

function writeFiles(file,clean) {
  var rootFolder = DriveApp.getFolderById("ID HERE");
  var subFolders = rootFolder.getFolders();  

  var testResult = false;
  while(subFolders.hasNext() == true){
    var folders = subFolders.next();
    if(folders == clean) {
      testResult = true;
    }
  }

  if(testResult == false){
    rootFolder.createFolder(clean);
  }   
  var destFolder = rootFolder.getFoldersByName(clean).next();

  if (destFolder.getFilesByName(file.getName()).hasNext() == false){
    destFolder.createFile(file);
  } else {
    var warning = Browser.msgBox("Warning", "This PDF already exists. If you wish to overwrite this file, press OK to continue.", Browser.Buttons.OK_CANCEL);
    if (warning == "ok"){
      destFolder.getFilesByName(file.getName()).next().setTrashed(true);
      destFolder.createFile(file);
    }
  }
}

下方编辑

经过一番戳戳和测试之后,似乎无论是使用URL来创建PDF还是使用getAs函数,都始终会忽略隐藏的工作表.

After some poking and prodding and testing, it seems when either using a URL to create a PDF, or the getAs function, hidden sheets are always omitted.

一个简单的测试:

function whatever() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var pdf = ss.getAs('application/pdf'); 
  var rootFolder = DriveApp.getFolderById("ID HERE");
  rootFolder.createFile(pdf);
}

如果该电子表格中有任何隐藏的工作表,它们将被错过.这是设计使然还是错误?

If you have any hidden sheets in that spreadsheet, they will be missed out. Is this by design or a bug?

我正在使用URL方法,在其中可以显式定义所需工作表的GID,并且我拥有电子表格,因此它应该可以工作吗?

I'm using the URL method in which I can explicitly define the GID of the sheet I want, and I own the spreadsheet, so should it work?

与另一位SO用户讨论后,我已经向Google提出了这个问题.

After discussions with another SO user, I've asked that very question to Google.

提交给Google的错误报告

推荐答案

尝试取消隐藏"工作表,使用"工作表,然后在完成后隐藏"工作表.有一个.hideSheet()方法,但API文档中没有列出.unhideSheet().

Try 'unhiding' the sheet, 'using' the sheet, and then 'hiding' the sheet when done. There is a .hideSheet() method, but there is no .unhideSheet() listed on their API documentation.

使用.activate()方法隐藏"工作表.

to 'unhide' the sheet use the .activate() method.

================

================

根据API文档:

activate()

activate()

激活此工作表.不更改工作表本身,仅更改活动工作表的父级概念."

"Activates this sheet. Does not alter the sheet itself, only the parent's notion of the active sheet."

// This example assumes there is a sheet named "first"
 var ss = SpreadsheetApp.getActiveSpreadsheet();
 var first = ss.getSheetByName("first");
 first.activate();

以下是API文档链接: https://developers.google .com/apps-script/reference/spreadsheet/sheet#activate

Here is the API documentation link: https://developers.google.com/apps-script/reference/spreadsheet/sheet#activate

如果他们解释了为什么您需要在文档中更改活动表的父级概念",而他们却没有这样做,那就太好了.

It would be nice if they explained why you would need to alter "the parent's notion of an active sheet" in the docs but they don't.

这篇关于隐藏工作表会导致Google表格的Export-sheet-as-PDF URL的输出损坏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆