【问题标题】:Google Sheet API V4 - Google Apps script - Sheets.Spreadsheets.Values.update - append DateGoogle Sheet API V4 - Google Apps 脚本 - Sheets.Spreadsheets.Values.update - 追加日期
【发布时间】:2021-05-03 21:03:39
【问题描述】:

我正在使用 Sheets.Spreadsheets.Values.update 将值粘贴到工作表中(由于使用 range.setValues() 的性能问题。

在日期的情况下,源值是日期对象(当我使用 range.setValues([[]]) 时可以很好地粘贴。

现在的最终结果是带有日期字符串版本的单元格,例如,Mon Feb 28 00:00:00 GMT+01:00 2022 不对应于有效的 gsheet 日期。我已经尝试了一些选项,但找不到可行的方法。

【问题讨论】:

    标签: google-apps-script google-sheets google-sheets-api


    【解决方案1】:

    我相信你的目标如下。

    • 您希望使用带有 Google Apps 脚本的 Sheets API 将值放入 Google 电子表格。
    • 在您当前的问题中,值包括日期对象。当使用spreadsheets.values.update 方法放置此日期对象时,该值不能用作日期对象。您想解决此问题。

    为了达到你的目的,把日期对象转换成其他的值怎么样?

    模式一:

    在此模式中,日期对象被转换为序列号并放入电子表格中。

    const spreadsheetId = "###";  // Please set the Spreadsheet ID.
    const values = [[new Date(), "b1", "c1"], [new Date(), "b2", "c2"]]; // This is a sample value for replicating your issue.
    
    // Here, the date values are converted to the serial number.
    const convertedValues = values.map(r => r.map(c => c instanceof Date ? (c.getTime() / 1000 / 86400) + 25569 : c));
    
    Sheets.Spreadsheets.Values.update({values: convertedValues}, spreadsheetId, "Sheet1", {valueInputOption: "USER_ENTERED"});
    
    • (c.getTime() / 1000 / 86400) + 25569 用于从 unix 时间转换为序列号,引用自 this answer
    • 在此脚本中,日期对象作为序列号。因此,请将“A”列的数字格式设置为日期时间。这样,序列号就可以看作是日期时间。

    模式2:

    在此模式中,日期对象被转换为字符串值,以便解析为日期对象并放入电子表格中。

    const spreadsheetId = "###";  // Please set the Spreadsheet ID.
    const values = [[new Date(), "b1", "c1"], [new Date(), "b2", "c2"]]; // This is a sample value for replicating your issue.
    
    // Here, the date values are converted to the string value for parsing as the date object.
    const convertedValues = values.map(r => r.map(c => c instanceof Date ? Utilities.formatDate(c, Session.getScriptTimeZone(), "yyyy/MM/dd HH:mm:ss") : c));
    
    Sheets.Spreadsheets.Values.update({values: convertedValues}, spreadsheetId, "Sheet1", {valueInputOption: "USER_ENTERED"});
    
    • 在此脚本中,日期对象作为字符串值被USER_ENTERED解析为日期对象。
    • 此示例使用yyyy/MM/dd HH:mm:ss 作为日期格式。当此格式无法解析时,请根据您的情况进行修改。

    参考资料:

    【讨论】:

    • 感谢@Tanaike 的彻底回复。我使用了模式 1,它确实粘贴了日期(序列号)。但是,在我的情况下,我需要日期与用户时区保持不变。所以我添加了时区差异(c.getTime() - c.getTimeZoneOffset()*1000*60 )/ 1000 / 86400+ 25569 ,它起作用了。现在我还需要使用 Sheets 服务而不是 setValues() 来处理异步问题
    • @ajoposor 感谢您的回复。很高兴您的问题得到解决。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-14
    相关资源
    最近更新 更多