无法将数据从csv传输到工作表

bmp9r5qi  于 2023-03-05  发布在  其他
关注(0)|答案(1)|浏览(164)
files = {1:'a', 2:'b', 3:'c', 4:'d', 5:'e', 6:'f', 7:'g'}
    COLUMNS = ['cs_mallId', 'counts']

    responseDf = pd.read_csv('/path/to/the/csv', usecols=COLUMNS)
    tokenPath='path/to/.token.json'
    scopes = ['https://www.googleapis.com/auth/spreadsheets',
            'https://www.googleapis.com/auth/drive']

    creds = service_account.Credentials.from_service_account_file(tokenPath)
    service = build('sheets', 'v4', credentials=creds)

    gc = pygsheets.authorize(service_account_file = tokenPath)
    gs = gc.open('name of Google sheet')
    sheet = gs.worksheet_by_title('name of worksheet')
    SPREADSHEET_ID = "worksheet ID"
    
    for mallId in files.keys():
        filteredDf = responseDf.loc[responseDf['cs_mallId'].isin(list(str(mallId)))]
        responseDf_countValues = filteredDf['counts'].tolist()
        responseDfRowCount = len(responseDf_countValues)
        print("responseDf_countValues : ", responseDf_countValues)

        row_offset = (mallId - 1) * 10
        range_name_resp = 'X' + str(5 + row_offset)  # for CSV file 1
        body = {
        'range': f'worksheet_name!{range_name_resp}',
        'values': responseDf_countValues,
        'majorDimension': 'ROWS'
        }
        print(body)
       
        response = service.spreadsheets().values().update(
        spreadsheetId=SPREADSHEET_ID,
        range=body['range'],
        valueInputOption='RAW',
        body=body,
        ).execute()

在这里,我试图添加数据从我的csv到一个特定列的工作表。每当我执行我的代码,它运行成功,直到结束'body'变量,但抛出一个错误,而最后发送响应到工作表。所以,这就是我得到一个错误说:-

Traceback (most recent call last):
    File "icrReports/icr_report_csv_to_sheets.py", line 374, in <module>
    icr_total_inv_categories(folderPath)
    File "icrReports/icr_report_csv_to_sheets.py", line 348, in   icr_total_inv_categories
    raise e
    File "icrReports/icr_report_csv_to_sheets.py", line 332, in

icr_total_inv_categories响应=服务.电子表格().值().更新(文件“/home/kartik/OCR/icr-微服务/环境/库/python3.8/站点-包/googleapiclient/helpers.py”,第130行,在位置 Package 器中返回 Package 的(*args,**kwargs)文件“/home/kartik/OCR/icr-微服务/环境/库/python3.8/站点-包/googleapiclient/http.py“,第938行,在执行过程中引发HttpError(响应,内容,uri=self.uri)googleapiclient.errors.HttpError:〈HttpError 400当请求https://sheets.googleapis.com/v4/spreadsheets/1ywjmlMCao0w5WYHBeVsVcaTTbylfICXixH5zs8CABmw/values/Sheet57%21X5?valueInputOption=RAW&alt=json时返回“数据.值[0]”处的无效值(类型。googleapis.com/google.protobuf.ListValue),38 "数据.值[1]“处的无效值(类型。googleapis.com/google.protobuf.ListValue),47"数据.值[2]”处的无效值(类型。googleapis.com/google.protobuf.ListValue),62“数据.值[3]”处的值无效(类型。googleapis.com/google.protobuf.ListValue),118 "数据.值[4]“处的值无效(类型。googleapis.com/google.protobuf.ListValue),51”数据.值[5]“处的值无效,36 "数据。值[6]“(类型。googleapis.com/google.protobuf.ListValue)处的值无效,3”。
详细信息:“[{'@ type':“类型错误请求”,“字段违规”:[{“字段”:“数据.值[0]”,“说明”:“”数据.值[0]“(类型. googleapis.com/google.protobuf.ListValue)处的无效值,38”},{“字段”:“数据.值[1]”,“说明”:“”数据.值[1]“(类型. googleapis.com/google.protobuf.ListValue)处的无效值,47”},{“字段”:“数据.值[2]”,“说明”:“”数据.值[2]“(类型. googleapis.com/google.protobuf.ListValue)处的值无效,62”},{“字段”:“数据.值[3]”,“说明”:“”数据.值[3]“(类型. googleapis.com/google.protobuf.ListValue)处的值无效,118”},{“字段”:“数据.值[4]”,“说明”:“”数据.值[4]“(类型. googleapis.com/google.protobuf.ListValue)处的无效值,51”},{“字段”:“数据.值[5]”,“说明”:“”数据.值[5]“(类型. googleapis.com/google.protobuf.ListValue)处的值无效,36”},{“字段”:“数据.值[6]”,“说明”:“”数据.值[6]“(类型. googleapis.com/google.protobuf.ListValue)处的值无效,3”}]}]“〉
请让我知道我做错了什么。谢谢。

o4hqfura

o4hqfura1#

您提供的错误消息显示传递给update()方法的值存在问题。具体而言,该错误消息指出,data.values列表中的多个值存在"无效值"错误。
根据我使用gsheets的经验,这个错误的一个可能原因是responseDf_countValues中的值的格式或类型不正确,Google Sheets API无法接受它们。
我会检查responseDf_countValues中的值,以确保它们的格式和类型符合Google Sheets API。您可以打印出responseDf_countValues列表,然后将其传递给update()方法检查值。
您还应该仔细检查body变量中range参数的格式,确保它与您要更新的Google工作表中range的格式相匹配。
希望这对你有帮助!祝你好运!
编辑:
也许我们可以尝试使用NumPy中的reshape()方法将responseDf_countValues列表重新整形为2D列表。

import numpy as np # Import numpy for reshape()

files = {1:'a', 2:'b', 3:'c', 4:'d', 5:'e', 6:'f', 7:'g'}
COLUMNS = ['cs_mallId', 'counts']

responseDf = pd.read_csv('/path/to/the/csv', usecols=COLUMNS)
tokenPath='path/to/.token.json'
scopes = ['https://www.googleapis.com/auth/spreadsheets',          'https://www.googleapis.com/auth/drive']

creds = service_account.Credentials.from_service_account_file(tokenPath)
service = build('sheets', 'v4', credentials=creds)

gc = pygsheets.authorize(service_account_file = tokenPath)
gs = gc.open('name of Google sheet')
sheet = gs.worksheet_by_title('name of worksheet')
SPREADSHEET_ID = "worksheet ID"

for mallId in files.keys():
    filteredDf = responseDf.loc[responseDf['cs_mallId'].isin(list(str(mallId)))]
    responseDf_countValues = filteredDf['counts'].tolist()
    responseDfRowCount = len(responseDf_countValues)
    print("responseDf_countValues : ", responseDf_countValues)

    row_offset = (mallId - 1) * 10
    range_name_resp = 'X' + str(5 + row_offset)  # for CSV file 1

    # reshape the list into a 2D list 
    values = np.array(responseDf_countValues).reshape(-1, 1).tolist()

    body = {
        'range': f'worksheet_name!{range_name_resp}',
        'values': values,
        'majorDimension': 'ROWS'
    }
    print(body)

    response = service.spreadsheets().values().update(
        spreadsheetId=SPREADSHEET_ID,
        range=body['range'],
        valueInputOption='RAW',
        body=body,
    ).execute()

这应该按预期工作,并使用CSV文件中的值更新工作表。

相关问题