【问题标题】:How to use ValueRenderOption in google-api-python-client for google sheets如何在 google-api-python-client 中为 Google 表格使用 ValueRenderOption
【发布时间】:2016-08-09 15:36:44
【问题描述】:

这是一个代码sn-p:

import ast
from oauth2client import file, client, tools
from oauth2client.service_account import ServiceAccountCredentials
from httplib2 import Http
from apiclient.discovery import build
from apiclient import discovery

SCOPE = 'https://www.googleapis.com/auth/spreadsheets'
CREDJSON = "some-cred-file-downloaded-from-dev-console.json"

def google_credentials(jsoncred=CREDJSON, scope=SCOPE):
    return ServiceAccountCredentials.from_json_keyfile_name(jsoncred, scope)


def csv_arrays(creds, key):

    (SHEETS, sheets) = sheets_fetch(creds, key)

    wks = sheets
    def create_filename(arg):
        filename = key.prefix + "_" + arg.get("properties, {}).get("title","Sheet1")
        filename = filename.replace(" ", "_")
        print (filename)
        return filename
    return [(create_filename(ws), ast.literal_eval(repr(SHEETS.spreadsheets().values().get(spreadsheetId=key.key, range=(ws.get("properties", {}).get("title", "Sheet1"))).execute().get('values',[])))) for ws in wks] #.decode("utf-8")

def sheets_fetch(creds, key):
    print('Now doing:', key)
    SHEETS = build('sheets', 'v4', http=creds.authorize(Http()))
    sheet_metadata = SHEETS.spreadsheets().get(spreadsheetId=key.key).execute()
sheets = sheet_metadata.get('sheets', '')

    return (SHEETS, sheets)

获取单元格的内容没有问题。我的问题是它们已格式化(因为这是默认值)并且我希望它们未格式化?

如何在csv_array函数的return语句的查询中设置选项?

https://developers.google.com/sheets/reference/rest/v4/ValueRenderOption

附带说明一下,除了将字符串添加到列表之外,还有其他方法可以获取单元格值吗?

【问题讨论】:

    标签: google-api-python-client google-sheets-api


    【解决方案1】:

    要使用 python 客户端设置 UNFORMATTED_VALUE 的 valueRenderOption,请使用:

    SHEETS.spreadsheets().values().get(spreadsheetId=key.key, range=myRange, valueRenderOption='UNFORMATTED_VALUE').execute()

    此外,当使用 UNFORMATTED_VALUE 时,响应将按原样在表格中输入(例如,数字将是数字,布尔值将是布尔值,字符串将是字符串)。日期可以是字符串也可以是数字,具体取决于DateTimeRenderOption,有关将日期作为数字处理的更多信息,请参阅Date/Time Serial Numbers Guide

    由于值已经正确输入,您不需要使用 ast 或 repr 进行任何额外的解析。

    【讨论】:

    • 第一个版本有效。我需要同时删除 repr 和 ast 以使“将数据类型化为实际类型,而不是始终作为字符串”你能更新你的答案以便我接受吗?
    猜你喜欢
    • 2016-03-11
    • 1970-01-01
    • 2020-07-22
    • 2021-10-11
    • 1970-01-01
    • 2011-08-12
    • 2017-09-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多