【问题标题】:Google sheet API multiple ranges parsingGoogle sheet API 多范围解析
【发布时间】:2016-11-29 08:26:53
【问题描述】:

我正在尝试使用刚刚与我的应用程序合并的 Google 电子表格 API。假设我有这个工作表

https://docs.google.com/spreadsheets/d/1TfRWRh0l09cxZ4HqwYWhRiBK4Lll3Jvj0XHpO-KEK2E/edit#gid=0

我想将这两个数据范围解析为 1 个输出表:姓名、年龄、爱好、职业、学校和性别。我将如何编写代码来区分数据范围 1 和 2?

代码如下:

private List<String> getDataFromApi() throws IOException {
    String spreadsheetId = "1TfRWRh0l09cxZ4HqwYWhRiBK4Lll3Jvj0XHpO-KEK2E";
    String range = "test!A3:D6,B10:C13";
    List<String> results = new ArrayList<String>();
    ValueRange response = this.mService.spreadsheets().values()
            .get(spreadsheetId, range)
            .execute();
    List<List<Object>> values = response.getValues();
    if (values != null) {
        results.add("Name, Age, Hobby, Occupation, School, Gender");
        for (List row : values) {
            results.add(row.get(0) + ", " + row.get(1) + ", " + row.get(2) + ", " + row.get(3)); //then i'm stuck//
        }
    }
    return results;
}

非常感谢!

【问题讨论】:

    标签: java arrays google-sheets google-api google-spreadsheet-api


    【解决方案1】:

    我会将数据移动到 2 个工作表/选项卡。由于您很可能有 2 个同名的人,因此请为每个人分配一个唯一的 ID,该 ID 在两个数据源之间是一致的。然后使用this tutorial 中的一部分代码将数据读入对象,然后将其解析到第三张表中。要创建对象,请复制完整代码下以以下开头的部分:

    //////////////////////////////////////////////////////////////////////////////////////////
    //
    // The code below is reused from the 'Reading Spreadsheet data using JavaScript Objects'
    // tutorial.
    //
    //////////////////////////////////////////////////////////////////////////////////////////
    

    从那里您将调用getRowsData() 函数以从两个数据集中的每一个中获取数据。然后根据唯一 ID 合并数据并填充第三张工作表。但是,这样做的问题是您需要某种方式来触发它,并且您每次都将重写数据。

    也就是说,这一切都可以通过第三张表中的 3 个公式来完成,并且会实时保持最新状态。请参阅 this copy of your spreadsheet 的合并选项卡/工作表上的单元格 A1、E1 和 E2。

    这是您将用于 getRowsData() 函数的完整代码,从上面链接的站点复制:

    //////////////////////////////////////////////////////////////////////////////////////////
    //
    // The code below is reused from the 'Reading Spreadsheet data using JavaScript Objects'
    // tutorial.
    //
    //////////////////////////////////////////////////////////////////////////////////////////
    
    // getRowsData iterates row by row in the input range and returns an array of objects.
    // Each object contains all the data for a given row, indexed by its normalized column name.
    // Arguments:
    //   - sheet: the sheet object that contains the data to be processed
    //   - range: the exact range of cells where the data is stored
    //   - columnHeadersRowIndex: specifies the row number where the column names are stored.
    //       This argument is optional and it defaults to the row immediately above range;
    // Returns an Array of objects.
    function getRowsData(sheet, range, columnHeadersRowIndex) {
      columnHeadersRowIndex = columnHeadersRowIndex || range.getRowIndex() - 1;
      var numColumns = range.getEndColumn() - range.getColumn() + 1;
      var headersRange = sheet.getRange(columnHeadersRowIndex, range.getColumn(), 1, numColumns);
      var headers = headersRange.getValues()[0];
      return getObjects(range.getValues(), normalizeHeaders(headers));
    }
    
    // For every row of data in data, generates an object that contains the data. Names of
    // object fields are defined in keys.
    // Arguments:
    //   - data: JavaScript 2d array
    //   - keys: Array of Strings that define the property names for the objects to create
    function getObjects(data, keys) {
      var objects = [];
      for (var i = 0; i < data.length; ++i) {
        var object = {};
        var hasData = false;
        for (var j = 0; j < data[i].length; ++j) {
          var cellData = data[i][j];
          if (isCellEmpty(cellData)) {
            continue;
          }
          object[keys[j]] = cellData;
          hasData = true;
        }
        if (hasData) {
          objects.push(object);
        }
      }
      return objects;
    }
    
    // Returns an Array of normalized Strings.
    // Arguments:
    //   - headers: Array of Strings to normalize
    function normalizeHeaders(headers) {
      var keys = [];
      for (var i = 0; i < headers.length; ++i) {
        var key = normalizeHeader(headers[i]);
        if (key.length > 0) {
          keys.push(key);
        }
      }
      return keys;
    }
    
    // Normalizes a string, by removing all alphanumeric characters and using mixed case
    // to separate words. The output will always start with a lower case letter.
    // This function is designed to produce JavaScript object property names.
    // Arguments:
    //   - header: string to normalize
    // Examples:
    //   "First Name" -> "firstName"
    //   "Market Cap (millions) -> "marketCapMillions
    //   "1 number at the beginning is ignored" -> "numberAtTheBeginningIsIgnored"
    function normalizeHeader(header) {
      var key = "";
      var upperCase = false;
      for (var i = 0; i < header.length; ++i) {
        var letter = header[i];
        if (letter == " " && key.length > 0) {
          upperCase = true;
          continue;
        }
        if (!isAlnum(letter)) {
          continue;
        }
        if (key.length == 0 && isDigit(letter)) {
          continue; // first character must be a letter
        }
        if (upperCase) {
          upperCase = false;
          key += letter.toUpperCase();
        } else {
          key += letter.toLowerCase();
        }
      }
      return key;
    }
    
    // Returns true if the cell where cellData was read from is empty.
    // Arguments:
    //   - cellData: string
    function isCellEmpty(cellData) {
      return typeof(cellData) == "string" && cellData == "";
    }
    
    // Returns true if the character char is alphabetical, false otherwise.
    function isAlnum(char) {
      return char >= 'A' && char <= 'Z' ||
        char >= 'a' && char <= 'z' ||
        isDigit(char);
    }
    
    // Returns true if the character char is a digit, false otherwise.
    function isDigit(char) {
      return char >= '0' && char <= '9';
    }
    

    【讨论】:

    • 谢谢@Karl_S 这太棒了!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-15
    • 2017-07-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多