【问题标题】:How can control the date format when generating a google docs (PDF) from a google spreadsheet with script?从带有脚本的谷歌电子表格生成谷歌文档(PDF)时如何控制日期格式?
【发布时间】:2016-06-05 12:43:59
【问题描述】:

我使用带有 Google Docs 的脚本和模板从一张 Google 表格(填充有 Google 表单)生成 PDF 文件。 但是这样做我发现在谷歌表格中的日期是 dd/mm/yyyy 格式,而在最终的 PDF 中是这样的 = Sat Feb 27 2016 00:00:00 GMT+0100 (CET)

脚本的“核心”是(对于谷歌表格的每一行)

var copyFile = DriveApp.getFileById(TEMPLATE_ID).makeCopy(FileName);
var copyId = copyFile.getId();
var copyDoc = DocumentApp.openById(copyId);
var copyBody = copyDoc.getActiveSection();

for (;columnIndex < headerRow[0].length; columnIndex++) {
    copyBody.replaceText('%' + headerRow[0][columnIndex] + '%', RowData[i][columnIndex])
}

columnIndex = 0;

// Create the PDF file, rename it if required and delete the doc copy

copyDoc.saveAndClose();

var dir = DriveApp.getFoldersByName("PDF FOLDER").next();  
var newFile = dir.createFile(copyFile.getAs('application/pdf'));  

if (PDF_FILE_NAME !== '') {
    newFile.setName(FileName)
    copyFile.setTrashed(true)
}  

我可以在哪里(以及如何)控制日期类型的 RowData[i] 以获得 doc/PDF 文件中的正确格式? (在模板中,使用 %date name% 指令进行有效值替换)

谢谢 万尼

【问题讨论】:

    标签: date google-apps-script google-sheets pdf-generation google-docs


    【解决方案1】:

    当您在替换循环中将日期插入到文档中时,您应该将日期转换为格式化字符串。

    要使用的函数是Utilities.formatDatedocumented here

    使用起来非常简单,例如:

    var formattedDate = Utilities.formatDate(new Date(), "GMT", "yyyy-MM-dd");
    

    请注意,不要使用 GMT 或任何 GMT+XX 值,最好使用Session.getScriptTimeZone(),它将根据您的时区自动给出正确的值(即使在夏令时的情况下)。

    编辑:

    你也可以试试getDisplayValue(),它返回的值是a string representation of what is shown in a cell

    【讨论】:

      猜你喜欢
      • 2016-06-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-31
      • 1970-01-01
      相关资源
      最近更新 更多