google-apps-script - 使用脚本将 csv 文件导入到 google 表格

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

};

最佳答案

这个网站 ( 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);

}

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

关于google-apps-script - 使用脚本将 csv 文件导入到 google 表格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51326047/

相关文章:

google-apps-script - BigQuery 失败的自动化应用脚本

javascript - Google 协作平台 HTML Iframe(不是小工具)

javascript - 从 Google 应用程序脚本 html 模板呈现 html

javascript - 谷歌应用脚​​本: Cannot get data from object loaded from ScriptDB

google-apps-script - var userProperties = PropertiesService.getUserProperties();不适合我?

google-apps-script - 根据事件标题删除 Google 日历事件

unit-testing - 测试 Gmail 插件

google-apps-script - 使用google脚本和查询功能构建google图表

google-apps-script - 在字符串中查找文本,不区分大小写

javascript - Google Sheets 在单独的电子表格之间移动行不起作用,但在工作表之间移动行正常