使用脚本将 csv 文件导入谷歌表格

Rob*_*279 1 google-apps-script

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

ItemID  Date    Source name Title   URL Created ItemSourceType
Run Code Online (Sandbox Code Playgroud)

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

Date    Writer  Status  Geog/Area/Product   Source  Title   Note
Run Code Online (Sandbox Code Playgroud)

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

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

我已将以下代码放在一起 - 其中一些代码一直在测试并试图拆分出一个 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) 
}
Run Code Online (Sandbox Code Playgroud)

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

我正在努力解决的部分是使用数组以正确的顺序使用字段填充电子表格,我将数组放在下面。

  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 );
Run Code Online (Sandbox Code Playgroud)

};

小智 7

看起来这个站点(https://ctrlq.org/code/20279-import-csv-into-google-spreadsheet)确实包含了几种将 CSV 导入谷歌电子表格的方法。

例如从谷歌驱动器导入,你可以这样做:

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

}
Run Code Online (Sandbox Code Playgroud)

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