如何在Google Apps脚本中导出到CSV时保持日期格式 [英] How to maintain date format in export to CSV in Google Apps Script

查看:20
本文介绍了如何在Google Apps脚本中导出到CSV时保持日期格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用Google Apps脚本中的以下函数将Google电子表格导出到CSV。是否可以保留CSV中的日期格式?

如果我改用菜单选项以CSV格式下载,日期格式将保持不变。

我正在使用以下函数导出到CSV:

function exportToCSV(file) {

  // Get the selected range in the spreadsheet
  var ws = SpreadsheetApp.openById(file.getId()).getSheets()[0];
  var range = ws.getRange(1,1,ws.getLastRow(),ws.getLastColumn())

  try {
    var data = range.getValues();

    var csvFile = undefined;

    // Loop through the data in the range and build a string with the CSV data
    if (data.length > 1) {
      var csv = "";
      for (var row = 0; row < data.length; row++) {
        for (var col = 0; col < data[row].length; col++) {
          if (data[row][col].toString().indexOf(",") != -1) {
            data[row][col] = """ + data[row][col] + """;
          }
        }

        // Join each row's columns
        // Add a carriage return to end of each row, except for the last one
        if (row < data.length-1) {
          csv += data[row].join(",") + "
";
        }
        else {
          csv += data[row];
        }
      }
      csvFile = csv;

    }
  }
  catch(err) {
    Logger.log(err);
    Browser.msgBox(err);
  }

  return csvFile;

}

推荐答案

更改:

    for (var col = 0; col < data[row].length; col++) {
      if (data[row][col].toString().indexOf(",") != -1) {
        data[row][col] = """ + data[row][col] + """;
      }
    }

至此(添加一行):

    for (var col = 0; col < data[row].length; col++) {
      data[row][col] = isDate(data[row][col]);      // Format, if date
      if (data[row][col].toString().indexOf(",") != -1) {
        data[row][col] = """ + data[row][col] + """;
      }
    }
您需要添加这些实用程序,我从this answer复制了这些实用程序。isDate()函数源于Martin Hawksey的Google Apps event managerisValidDate()函数在另一个SO答案中找到,如评论中所述。

isDate()中的日期格式可以根据您的需要进行更改。有关详细信息,请参阅Utilities.formatDate()

// From https://stackoverflow.com/questions/1353684
// Returns 'true' if variable d is a date object.
function isValidDate(d) {
  if ( Object.prototype.toString.call(d) !== "[object Date]" )
    return false;
  return !isNaN(d.getTime());
}

// Test if value is a date and if so format
// otherwise, reflect input variable back as-is. 
function isDate(sDate) {
  if (isValidDate(sDate)) {
    sDate = Utilities.formatDate(new Date(sDate), TZ, "dd MMM yy HH:mm");
  }
  return sDate;
}

这篇关于如何在Google Apps脚本中导出到CSV时保持日期格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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