【问题标题】:Validation for null values验证空值
【发布时间】:2020-07-14 18:14:17
【问题描述】:

我正在 Google Apps Scipt 编辑器中编写代码以将数据从 Google 表格导出到 Google Firebase。现在,我必须硬编码我拥有的确切数据行数。如何编辑我的代码以继续浏览 Google 表格,直到遇到空行?

//Create a menu item for 'Export to Firestore'
function onOpen() {
  SpreadsheetApp.getUi().createMenu('???? Firebase').addItem('Export to Firestore', 'main').addToUi();
}

function main() {
  //Get the active spreadsheet and its name for the collection name
  var sheet = SpreadsheetApp.getActiveSheet();
  var sheetName = sheet.getName();
  
  //Get the first row as object properties
  // ['Author', 'ISBN', 'Category', 'Title']
  var properties = getProperties(sheet);
  
  //Get the next 4 rows as records
  //[ ['Hansley Ford', '34787426409', 'Drama', 'Grim Peeks'], ..., ...]
  var records =  getRecords(sheet);
  
  //Export to Firestore
  var firestore = FirestoreApp.getFirestore('','','');
  
   
  exportToFirestore(firestore, sheetName, properties, records);
}
function exportToFirestore(firestore, collectionName, properties, records) {
  records.map(function(record) {
    //record: ['Hansley Ford', '34787426409', 'Drama', 'Grim Peeks']
    //props: ['Author', 'ISBN', 'Category', 'Title']
    var data = {};
    properties.forEach(function(prop,i) { data[prop] = record[i]; });
    return data;
  }).forEach(function(data) {
    firestore.createDocument(collectionName, data);
  });
}

function getProperties(sheet) {
  return sheet.getRange(1, 1, 1, 4).getValues()[0]; //['Author', 'ISBN', 'Category', 'Title']
}


【问题讨论】:

    标签: javascript arrays google-apps-script google-sheets


    【解决方案1】:

    您可以使用 Class Sheet getDataRange() 获取数据范围(从左上角单元格到最后一行和最后一列的右下角单元格有值)。然后你可以使用 Class Range getValues() 来获取范围值,你可以使用 values.length 来知道有多少行有这个范围,或者你可以使用 Class Range getLastRow()

    您也可以使用 Class Sheet getLastRow() 获取最后一行。

    参考

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-10-13
      • 2020-06-11
      • 1970-01-01
      • 2013-07-21
      • 2020-01-22
      • 2014-04-29
      • 2018-01-26
      相关资源
      最近更新 更多