【问题标题】:How to get around Google Sheets V4 API not returning empty cells如何绕过 Google Sheets V4 API 不返回空单元格
【发布时间】:2016-07-15 14:18:50
【问题描述】:

我有一个包含几列的谷歌表格。我们使用它来保存测试帐户的登录名/密码组合。我被要求每 90 天自动更改每个帐户的密码,以满足 IT 要求。

我决定使用 Java 和 GoogleSheets V4 API。我需要打开工作表并收集所有行并遍历它们。对于每一行,获取登录 ID 和密码,生成新密码,更改密码,然后写回新密码和旧密码所在的行。

现在,我的绊脚石是对于连续没有内容的单元格,它不会返回任何内容。因此,一行将有 5 列,而一行将有 4 列。而且我无法知道哪一列是空的,因此没有返回。

有没有办法让它返回甚至是空的单元格?

    range = "'Functional Users'!A" + rowCount + ":E" + rowCount;
    response = service.spreadsheets().values().get(spreadsheetId, range).execute();
    values = response.getValues();
    cells = values.get(0);
    while (cells != null || cells.size() != 0)
    {
        //Iterate through the columns in the row (NOTE: If a column is blank, it will be missing here)
        //Cells(0) = Domain
        //Cells(1) = Ignored
        //Cells(2) = Account Name
        //Cells(3) = Email
        //Cells(4) = Password Status (Soon to be deprecated)
        if (cells.size() == 5)
        {

【问题讨论】:

  • 我遇到了同样的问题 - 您找到解决方案了吗?

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


【解决方案1】:

我有一个类似的用例,并使用“CellFeeds”来解决这个问题。

我从 Google 电子表格中提取了所有行和列,但遇到了一个问题,即空/空值被遗漏并且列数总是受到影响。

您可以尝试将“return-empty=true”作为查询参数添加到 CellFeed 的 URL。它将空值作为 null 返回,而不是绕过它们。

您可以参考this page 了解有关使用基于单元的 Feed 的详细文档。

以下代码可能会帮助您解决您的问题:

SpreadsheetService service =
    new SpreadsheetService("MyService");

URL SPREADSHEET_FEED_URL = new URL(
    "https://spreadsheets.google.com/feeds/cells/"+ "SpreadSheetID" +"/default/public/values");  //Replace SpreadSheetID with your spreadsheet ID, Note: Here the spreadsheet is shared publicly. If it is not published publicly, you need to change the URL and also workaround with the API keys.

// Fetch the first 10 rows of the spreadsheet
URL cellFeedUrl;
try {
    cellFeedUrl = new URI(SPREADSHEET_FEED_URL.toString()
        + "?return-empty=true&min-row=1&max-row=10").toURL(); //Here, return-empty=true is important
    CellFeed cellFeed = service.getFeed(cellFeedUrl, CellFeed.class);

    // Iterate through each cell, printing its value.
    for (CellEntry cell : cellFeed.getEntries()) {
        System.out.println(cell.getCell().getValue() + "\t");
    }
}
catch (URISyntaxException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}

结果将为您提供前 10 行,包括空单元格为 null,而不影响列排列。

希望这会有所帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多