【问题标题】:How to maintain date format in export to CSV in Google Apps Script如何在 Google Apps 脚本中维护导出到 CSV 的日期格式
【发布时间】:2013-05-29 01:16:52
【问题描述】:

我正在尝试使用 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(",") + "\r\n";
        }
        else {
          csv += data[row];
        }
      }
      csvFile = csv;

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

  return csvFile;

}

【问题讨论】:

    标签: google-apps-script google-sheets export-to-csv


    【解决方案1】:

    改变这个:

        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 答案中找到,如 cmets 中所述。

    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;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-05-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多