隐藏的工作表导致Google表格的导出工作表作为PDF网址的输出损坏

时间:2016-01-16 12:54:42

标签: google-apps-script google-sheets

我创建了一个脚本来生成一些PDF,如果需要的话,将它们保存到驱动器并通过电子邮件发送给它们。

该脚本工作正常,除了一个问题:当我隐藏名为“TrafficAgentPDF”的工作表并运行我的脚本时,它会在Drive中创建PDF,但它以某种方式损坏了。无法通过谷歌打开;在浏览器中打开它时,它是空白的。取消隐藏工作表,一切正常。

TrafficAgentPDF表在另一张表上执行vlookup,以显示图像而不是值。图像是小图标,仅使用3个。红色交通灯,琥珀色交通灯和绿色。 (我以为我会提到这是一个奇怪的渲染问题。)

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

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函数,都会忽略隐藏的工作表。

一个简单的测试:

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

如果您在该电子表格中有任何隐藏的工作表,那么它们将被遗漏。这是设计还是错误?

我正在使用URL方法,我可以在其中明确定义我想要的工作表的GID,并且我拥有电子表格,所以它应该有效吗?

在与其他SO用户讨论后,我向谷歌提出了这个问题。

Bug report submitted to Google

2 个答案:

答案 0 :(得分:0)

尝试取消隐藏&#39;表格,&#39;使用&#39;表格,然后隐藏&#39;表格完成后。有一个.hideSheet()方法,但它们的API文档中没有列出.unhideSheet()。

去除&#39;取消隐藏&#39;工作表使用.activate()方法。

=====

根据API文档:

激活()

&#34;激活此工作表。不会改变工作表本身,只改变活动工作表的父级概念。&#34;

// 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

如果他们解释为什么你需要改变父母对活跃表格的概念,那就太好了。在文档中,但他们没有。

答案 1 :(得分:0)

我发现我写的脚本不适用于隐藏的工作表,因此经过一些研究发现这可以取消隐藏工作表:

  var ss = SpreadsheetApp.openByUrl("Google URL");

  var print1  = ss.getSheetByName("Print1"); // Sheetname is 'Print1'

// unhide sheet
   print1.showSheet().activate();
   ss.setActiveSheet(print1, true);

希望这有帮助!