简体   繁体   English

Google Apps 脚本将 Gmail CSV 导入工作表错误

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

I've pieced together this code from various google searches that will pull an e-mail's CSV attachment if the e-mail has a specific label.我已经从各种谷歌搜索中拼凑了这段代码,如果电子邮件具有特定标签,这些搜索将提取电子邮件的 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();                                                            

}

The script runs fine, however I am running into issues with cells that had values with commas or quotes.该脚本运行良好,但是我遇到了带有逗号或引号值的单元格的问题。 For example, if a cell has the following:例如,如果一个单元格具有以下内容:

1,000,000

or或者

Google "Apps" Script

It will return to following, respectively.它将分别返回以下。

\r\n

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

I'm certain it has to do with the Regex used, however I am not certain how to adjust for the above.我确定它与使用的正则表达式有关,但我不确定如何针对上述情况进行调整。 Any help with this would be greatly appreciated.对此的任何帮助将不胜感激。

I was able to use the original code (used in question) and replace the escaping and Utilities.parseCsv with code from this link.我能够使用原始代码(有问题使用)并将转义和 Utilities.parseCsv 替换为此链接中的代码。 This will properly import CSVs even if cells include quotes and commas:https://productforums.google.com/forum/#!topic/docs/nhXjrl8JIek即使单元格包含引号和逗号,这也会正确导入 CSV:https ://productforums.google.com/forum/#!topic/docs/nhXjrl8JIek

Here is my final code:这是我的最终代码:

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.

相关问题 从 gmail 附件导入 csv 到谷歌表 - import csv from gmail attachment to google sheet Apps 脚本:CSV 附件到 Google 表格错误 - 无法解析文本 - Apps Script: CSV attachment to Google Sheet error - Could not parse text 使用谷歌应用程序脚本导入 csv - import csv with google apps script 使用 Google 脚本按名称将 CSV 数据导入 Google 工作表 - 错误工作表未定义 - Import CSV data into Google sheet by NAME using Google Script - error Sheet is not defined 无法在 Google Apps 脚本中导入 CSV 数据。 怎么了? - Unable to Import CSV data in Google Apps Script. What is wrong? 从 Google Apps 脚本中的单列 CSV 文件导入数据 - Import data from a single column of CSV file in Google Apps Script 使用双引号从邮件 (Gmail) 解析 CSV 和? 使用 Google Apps 脚本的字符 - Parsing a CSV from a Mail (Gmail) with double quotes and ? characters with Google Apps Script 将日期列附加到从 Gmail CSV 文件导入的数组 Google Apps 脚本 - Append date column to array imported from Gmail CSV File Google Apps Script 使用 Google Apps 脚本将 CSV 文件从本地 PC 上传到 Google Sheet - Upload CSV file from local PC to Google Sheet using Google Apps Script 在谷歌应用脚​​本中使用/调用Google Sheet的嵌入式文件导入功能 - Using/Calling Google Sheet's embedded File Import function in google apps script
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM