简体   繁体   English

Google 表格 API v4 - 如何获取最后一行的值?

[英]Google Sheets API v4 - How to get the last row with value?

How to get the last row with value in the new Google Sheets API v4?如何在新的 Google 表格 API v4 中获取最后一行的值?

i use this to get a range from a sheet:我用它来从工作表中获取范围:

mService.spreadsheets().values().get("ID_SHEET", "Sheet1!A2:B50").execute();

how to detect the last row with value in the sheet?如何检测工作表中最后一行的值?

您可以将范围设置为“A2:D”,这将获取到工作表中的最后一个数据行。

I managed to get it by counting the total rows from current Sheets.我设法通过计算当前表格中的总行数来获得它。 Then append the data to the next row.然后将数据追加到下一行。

rowcount = this.mService.spreadsheets().values().get(spreadsheetId, range).execute().getValues().size()

Rather than retrieving all the rows into memory just to get the values in the last row, you can use the append API to append an empty table to the end of the sheet, and then parse the range that comes back in the response.您可以使用 append API 将一个空表附加到工作表的末尾,然后解析响应中返回的范围,而不是将所有行检索到内存中只是为了获取最后一行中的值。 You can then use the index of the last row to request just the data you want.然后您可以使用最后一行的索引来请求您想要的数据。

This example is in Python:这个例子是在 Python 中的:

#empty table
table = {
    'majorDimension': 'ROWS',
    'values': []
}

# append the empty table
request = service.spreadsheets().values().append(
    spreadsheetId=SPREADSHEET_ID,
    range=RANGE_NAME,
    valueInputOption='USER_ENTERED',
    insertDataOption='INSERT_ROWS',
    body=table)

result = request.execute()

# get last row index
p = re.compile('^.*![A-Z]+\d+:[A-Z]+(\d+)$')
match = p.match(result['tableRange'])
lastrow = match.group(1)

# lookup the data on the last row
result = service.spreadsheets().values().get(
    spreadsheetId=SPREADSHEET_ID,
    range=f'Sheetname!A{lastrow}:ZZ{lastrow}'
).execute()

print(result)

You don't need to.你不需要。 Set a huge range (for example A2:D5000 ) to guarantee that all your rows will be located in it.设置一个很大的范围(例如A2:D5000 )以保证您的所有行都将位于其中。 I don't know if it has some further impact, may be increased memory consumption or something, but for now it's OK.我不知道它是否有进一步的影响,可能是内存消耗增加或其他什么,但现在还可以。

private List<String> getDataFromApi() throws IOException {
        String spreadsheetId = "1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms"; 
        String range = "A2:D5000";
        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, Major");
            for (List row : values) {
                results.add(row.get(0) + ", " + row.get(3));
            }
        }
        return results;
    }

Look at the loop for (List row : values) .查看for (List row : values)的循环。 If you have two rows in your table you will get two elements in values list.如果您的表格中有两行,您将在values列表中获得两个元素。

😢 Google Sheets API v4 does not have a response that help you to get the index of the last written row in a sheet (row that all cells below it are empty). 😢 Google Sheets API v4 没有响应可以帮助您获取工作表中最后写入的行的索引(其下方所有单元格都为空的行)。 Sadly, you'll have to workaround and fetch all sheet rows' into memory (I urge you to comment if I'm mistaken)可悲的是,您必须解决方法并将所有工作表行提取到内存中(如果我弄错了,我敦促您发表评论)

Example:示例:

spreadsheet_id = '1TfWKWaWypbq7wc4gbe2eavRBjzuOcpAD028CH4esgKw'
range = 'Sheet1!A:Z'

rows = service.spreadsheets().values().get(spreadsheetId=spreadsheet_id, range=range).execute().get('values', [])
last_row = rows[-1] if rows else None
last_row_id = len(rows)
print(last_row_id, last_row)

Output:输出:

13 ['this', 'is ', 'my', 'last', 'row']

在此处输入图片说明


💡 If you wish to append more rows to the last row, see this 💡如果你想在最后一行追加更多的行,请看这个

Have a cell somewhere that doesn't interfere with your datarange with =COUNTA(A:A) formula and get that value.使用 =COUNTA(A:A) 公式在某个不会干扰您的数据范围的地方设置一个单元格并获取该值。 In your case在你的情况下

=MAX(COUNTA(A:A50),COUNTA(B:B50))

? ?

If there could be empty cells inbetween the formula would be a little more tricky but I believe it saves you some memories.如果公式之间可能有空单元格会有点棘手,但我相信它可以为您节省一些记忆。

2022 Update 2022 更新

II don't know if this will be relevant for someone in 2022, but now you can do it differently.我不知道这是否与 2022 年的某人有关,但现在你可以采取不同的方式。 You can just set next value as range :您可以将下一个值设置为 range :

const column = "A"
const startIndex = 2
const range = column + startIndex + ":" + column

In resolve you get all data in column and range with last index.在解析中,您将获得最后一个索引的列和范围中的所有数据。 I tested it on js and php我在js和php上测试过

Following Mark B's answer, I created a function that performs a dummy append and then extracts the last row info from the dummy append's response.按照 Mark B 的回答,我创建了一个 function,它执行虚拟 append,然后从虚拟追加的响应中提取最后一行信息。

def get_last_row_with_data(service, value_input_option="USER_ENTERED"):
    last_row_with_data = '1'
    try:

        dummy_request_append = service.spreadsheets().values().append(
            spreadsheetId='<spreadsheet id>',
            range="{0}!A:{1}".format('Tab Name', 'ZZZ'),
            valueInputOption='USER_ENTERED',
            includeValuesInResponse=True,
            responseValueRenderOption='UNFORMATTED_VALUE',
            body={
                "values": [['']]
            }
        ).execute()

        a1_range = dummy_request_append.get('updates', {}).get('updatedRange', 'dummy_tab!a1')
        bottom_right_range = a1_range.split('!')[1]
        number_chars = [i for i in list(bottom_right_range) if i.isdigit()]
        last_row_with_data = ''.join(number_chars)

    except Exception as e:
        last_row_with_data = '1'

    return last_row_with_data

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM