簡體   English   中英

Google Apps 腳本將 Gmail CSV 導入工作表錯誤

[英]Google Apps Script Gmail CSV Import to Sheet Error

我已經從各種谷歌搜索中拼湊了這段代碼,如果電子郵件具有特定標簽,這些搜索將提取電子郵件的 CSV 附件。

function importCSVFromGmail() { 
  //gets first(latest) message with set label
  var threads = GmailApp.getUserLabelByName('Dashboard Updates').getThreads(0,1);     
  var message = threads[0].getMessages()[0];
  var attachment = message.getAttachments()[0];

  // Is the attachment a CSV file
  if (attachment.getContentType() === "text/csv") {                            
    var ss = SpreadsheetApp.getActive();
    var sh = ss.getSheetByName("Monthly_Detail_Instantis");
    //parses content of csv to array
    var dataString = attachment.getDataAsString();
    var escapedString = dataString.replace(/(?=["'])(?:"[^"\\]*(?:\\[\s\S][^"\\]*)*"|'[^'\\]\r\n(?:\\[\s\S][^'\\]\r\n)*')/g, '\\r\\n');
    var csvData = Utilities.parseCsv(escapedString);

    // Remember to clear the content of the sheet before importing new data
    sh.clearContents().clearFormats();                                         
    //pastes array to sheet
    sh.getRange(1, 1, csvData.length, csvData[0].length).setValues(csvData);   
  }

  //marks the Gmail message as read and unstars it (Filter sets a star)
  message.markRead();                                                          
  message.unstar();                                                            

}

該腳本運行良好,但是我遇到了帶有逗號或引號值的單元格的問題。 例如,如果一個單元格具有以下內容:

1,000,000

或者

Google "Apps" Script

它將分別返回以下。

\r\n

\r\n\r\n\r\n

我確定它與使用的正則表達式有關,但我不確定如何針對上述情況進行調整。 對此的任何幫助將不勝感激。

我能夠使用原始代碼(有問題使用)並將轉義和 Utilities.parseCsv 替換為此鏈接中的代碼。 即使單元格包含引號和逗號,這也會正確導入 CSV:https ://productforums.google.com/forum/#!topic/docs/nhXjrl8JIek

這是我的最終代碼:

function importCSVFromGmail() { 
  //gets first(latest) message with set label
  var threads = GmailApp.getUserLabelByName('Dashboard Updates').getThreads(0,1);     
  var message = threads[0].getMessages()[0];
  var attachment = message.getAttachments()[0];

  // Is the attachment a CSV file
  if (attachment.getContentType() === "text/csv") {                            
    var ss = SpreadsheetApp.getActive();
    var sh = ss.getSheetByName("Monthly_Detail_Instantis");
    //parses content of csv to array
    var dataString = attachment.getDataAsString();
    var csvData = CSVToArray(dataString);

    // Remember to clear the content of the sheet before importing new data
    sh.clearContents().clearFormats();                                         
    //pastes array to sheet
    var lastRowValue = sh.getLastRow();
    for (var i = 0; i < csvData.length; i++) {
       sh.getRange(i+lastRowValue+1, 1, 1, csvData[i].length).setValues(new Array(csvData[i]));
    } 
  }

  //marks the Gmail message as read and unstars it (Filter sets a star)
  message.markRead();                                                          
  message.unstar();                                                            

}

//The code formats the code so it can be entered into the Google Script

function CSVToArray( strData, strDelimiter ){ 
  // Check to see if the delimiter is defined. If not,
  // then default to comma.
  strDelimiter = (strDelimiter || ",");

  // Create a regular expression to parse the CSV values.
  var objPattern = new RegExp(
    (
      // Delimiters.
      "(\\" + strDelimiter + "|\\r?\\n|\\r|^)" +


      // Quoted fields.
      "(?:\"([^\"]*(?:\"\"[^\"]*)*)\"|" +


      // Standard fields.
      "([^\"\\" + strDelimiter + "\\r\\n]*))"
    ),
    "gi"
  );


  // Create an array to hold our data. Give the array
  // a default empty first row.
  var arrData = [[]];

  // Create an array to hold our individual pattern
  // matching groups.
  var arrMatches = null;

  // Keep looping over the regular expression matches
  // until we can no longer find a match.
  while (arrMatches = objPattern.exec( strData )){

    // Get the delimiter that was found.
    var strMatchedDelimiter = arrMatches[ 1 ];

    // Check to see if the given delimiter has a length
    // (is not the start of string) and if it matches
    // field delimiter. If id does not, then we know
    // that this delimiter is a row delimiter.
    if (
      strMatchedDelimiter.length &&
      (strMatchedDelimiter != strDelimiter)
    ){

      // Since we have reached a new row of data,
      // add an empty row to our data array.
      arrData.push( [] );

    }

    // Now that we have our delimiter out of the way,
    // let's check to see which kind of value we
    // captured (quoted or unquoted).
    if (arrMatches[ 2 ]){

      // We found a quoted value. When we capture
      // this value, unescape any double quotes.
      var strMatchedValue = arrMatches[ 2 ].replace(
        new RegExp( "\"\"", "g" ),
        "\""
      );

    } else {

      // We found a non-quoted value.
      var strMatchedValue = arrMatches[ 3 ];

    }

    // Now that we have our value string, let's add
    // it to the data array.
    arrData[ arrData.length - 1 ].push( strMatchedValue );
  }

  // Return the parsed data.
  return( arrData );
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM