使用脚本将CSV文件导入Google表格

时间:2018-07-13 13:16:24

标签: google-apps-script

我面临以下问题。我将看到一个.csv文件,其中将包含以下字段:

ItemID  Date    Source name Title   URL Created ItemSourceType

但是我不需要所有字段,但是我需要将其导入到预定义的Google表格模板中,如下所示:

Date    Writer  Status  Geog/Area/Product   Source  Title   Note

同样,并非所有列都需要填充,因此最终解决方案应如下所示。

Date    Writer  Status  Geog/Area/Product   Source  Title   Note 
Today() NULL    NULL    Null                Site    Title-(hyperlinked with URL)   Null

我整理了以下代码-其中一些代码已经过测试,并试图拆分为CSV,并且我还没有尝试添加超链接字段。

function addData() {
  var fSource = DriveApp.getFolderById('138ZRbesgDkKHOROm4izD22oaXoanvsyJ'); // reports_folder_id = id of folder where csv reports are saved
  var sheet = SpreadsheetApp.getActiveSheet();
  var startRow = 12;  // First row of data to process
  var numRows = 2;   // Number of rows to process

  var fSource = DriveApp.getFolderById('138ZRbesgDkKHOROm4izD22oaXoanvsyJ'); // reports_folder_id = id of folder where csv reports are saved
  var fi = fSource.getFilesByName('data.csv'); // latest report file
  var ss = SpreadsheetApp.openById('1wBawJzQ3eAhyjCuetAFg7uUUrum6CDImBcVcxaZ9j84'); // data_sheet_id = id of spreadsheet that holds the data to be updated with new report data

  if ( fi.hasNext() ) { // proceed if "report.csv" file exists in the reports folder
    var file = fi.next();
    var csv = file.getBlob().getDataAsString();
    var csvData = CSVToArray(csv); 
    for ( var i=1, lenCsv=csvData.length; i<lenCsv; i++ ) {
      sheet.getRange(i+1, 1, 1, csvData[i].length).setValues(new Array(csvData[i]));
    }
  }


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


  // Fetch the range of cells A2:G3
  var dataRange = sheet.getRange(startRow, 1, numRows,8)//sheet.getRange(startRow, 1, numRows, 8)

  var data = dataRange.getValues();
  for (var i = 0; i < data.length; ++i) {
    var row = data[i];
    var ItemID = row[0]
    var Date = row[1]
    var SourceName = row[2]
    var Title = row[3]
    var URL = row[4]
    var Created = row[5]
    var ItemSourceType = row[6]
    sheet.getRange(i+1, 1, 1, csvData[i].length).setValues(new Array(csvData[i]));
  }

  var correctFormat = ItemID + ", " + Date + ", " + SourceName + ", " + Title + ", " + URL + ", " + Created + ", " + ItemSourceType;


  Logger.log(correctFormat) 
}

如果有人能够帮助我指出正确的方向,将不胜感激。

我为此苦苦挣扎的一部分是使用数组按正确的顺序将电子表格中的字段填充到电子表格中。

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

};

1 个答案:

答案 0 :(得分:1)

似乎该网站(https://ctrlq.org/code/20279-import-csv-into-google-spreadsheet)确实包含几种将CSV导入Google电子表格的方法。

例如,可以从Google Drive导入

function importCSVFromGoogleDrive() {

  var file = DriveApp.getFilesByName("data.csv").next();
  var csvData = Utilities.parseCsv(file.getBlob().getDataAsString());
  var sheet = SpreadsheetApp.getActiveSheet();
  sheet.getRange(1, 1, csvData.length, csvData[0].length).setValues(csvData);

}

之后,您将需要过滤所需的数据,但是我想一旦从csv导入数据,这样做会更容易。