2013-05-29 32 views
1

我試圖使用Google Apps腳本中的以下功能將Google電子表格導出爲CSV。是否可以維護CSV中的日期格式?如何在Google Apps腳本中將日期格式導出爲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; 

} 

回答

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 manager,並且isValidDate()函數在另一個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; 
} 
+0

完美。謝謝!! – rishim3

相關問題