简体   繁体   English

使用python将数据从csv文件解析到Google Spreadsheet

[英]Parsing data from csv file to Google Spreadsheet with python

I'm writing a python script to send data from a csv file to a Google Spreadsheet. 我正在编写一个python脚本,将数据从csv文件发送到Google Spreadsheet。 I'm have a clear understanding of the basics need for this project, however I'm totally lost regarding formatting/parsing data from a csv file to the google sheet (I'm still learning python !). 我对这个项目的基本需求有清晰的了解,但是我完全迷失了从CSV文件到Google表格的格式/解析数据(我还在学习python!)。

So here is the first part of my code : 所以这是我的代码的第一部分:

def add_todo():

    credentials = get_credentials()
    http = credentials.authorize(httplib2.Http())
    discoveryUrl = ('https://sheets.googleapis.com/$discovery/rest?'
                    'version=v4')
    service = discovery.build('sheets', 'v4', http=http,
                              discoveryServiceUrl=discoveryUrl)

    spreadsheetId = 'spreadsheetidhere'
    rangeName = 'A1:A'
    # https://developers.google.com/sheets/guides/values#appending_values
    values = {'values':[['Hello Saturn',],]}
    result = service.spreadsheets().values().append(
        spreadsheetId=spreadsheetId, range=rangeName,
        valueInputOption='RAW',
        body=values).execute()

if __name__ == '__main__':
    add_todo()

I didn't write it myself and it's working perfectly. 我不是自己写的,它运行良好。

Here is the second part of my code : 这是我的代码的第二部分:

test = []
with open('data.csv', 'rb') as f:
    reader = csv.reader(f)
    for row in reader:
            test.append(row)

It's also working properly, even though I don't really know how I should mix it with the first part of my code. 即使我真的不知道如何将其与代码的第一部分混合,它也可以正常工作。 I've done this: 我已经做到了:

test = []

def add_todo():
    with open('snap.csv', 'rb') as f:
        reader = csv.reader(f)
        for row in reader:
                test.append(row)
    credentials = get_credentials()
    http = credentials.authorize(httplib2.Http())
    discoveryUrl = ('https://sheets.googleapis.com/$discovery/rest?'
                    'version=v4')
    service = discovery.build('sheets', 'v4', http=http,
                              discoveryServiceUrl=discoveryUrl)

    spreadsheetId = '1UJGs-gJCIUDv5jg5-p0MPEqsokYu5k2MfJ8A5oBkpWs'
    rangeName = 'A1:A'

    # https://developers.google.com/sheets/guides/values#appending_values
    values = {'values':[['Hello Saturn',],]}
    result = service.spreadsheets().values().append(
        spreadsheetId=spreadsheetId, range=rangeName,
        valueInputOption='RAW',
        body=values).execute()

if __name__ == '__main__':
    add_todo()

As you can guess my main concern is how I should proceed to pass the data from the test array to the spreadsheet values values = {'values':[['Hello Saturn',],]} 如您所料,我主要关心的是如何继续将数据从test数组传递到电子表格中values values = {'values':[['Hello Saturn',],]}

I wanted to do something like this : values = {'values':[test]} but obviously it doesn't work. 我想做这样的事情: values = {'values':[test]}但显然不起作用。

To sum up, here is my csv file : 总结一下,这是我的csv文件:

data1,data2,data3,data4,...
value1x,value2x,value3x,value4x,...
value1y,value2y,value3y,value4y,...
value1z,value2z,value3z,value4z,...

And here is what I want in my spreadsheet : 这是我想要在电子表格中显示的内容:

data1   data2   data3   data4 //col name
value1x value2x value3x value4x //row1
value1y value2y value3y value4y //row2
etc...

I'm totally lost between array , list , json format. 我完全迷失在arraylist ,json格式之间。

You need to specify the range parameter and body in the main API call. 您需要在主API调用中指定range参数和body If you look at the API documentation you'll see that the body needs to have the following form 如果您查看API文档 ,就会发现body需要采用以下形式

values = [
    [
        # Cell values ...
    ],
    # Additional rows ...
]
body = {
  'values': values
}

That is, a dictionary with one element values that is a list of lists. 即,具有一个元素values的字典是列表的列表。 Your test variable that contains the CSV data already appears to be a list of lists, so you're good to go. 包含CSV数据的test变量似乎已经是列表列表,因此您可以继续进行。 You don't need to worry about JSON here, since the API's Python interface automatically translates your Python dictionaries and lists to JSON. 您无需在此担心JSON,因为API的Python接口会自动将您的Python字典和列表转换为JSON。 The range parameter is a bit trickier but based on the docs using the sheet's name will make it append the values to the end of that sheet. range参数有些棘手,但是基于使用工作表名称的文档,它将使值附加到工作表的末尾。 So, putting the above together, your code might look something like this (I have not tested it): 因此,将以上内容放在一起,您的代码可能看起来像这样(我尚未对其进行测试):

def add_todo():
    test = []  # test should be initialized in the function body
    with open('snap.csv', 'rb') as f:
        reader = csv.reader(f)
        for row in reader:
                test.append(row)
    credentials = get_credentials()
    http = credentials.authorize(httplib2.Http())
    discoveryUrl = ('https://sheets.googleapis.com/$discovery/rest?'
                    'version=v4')
    service = discovery.build('sheets', 'v4', http=http,
                              discoveryServiceUrl=discoveryUrl)

    spreadsheetId = '1UJGs-gJCIUDv5jg5-p0MPEqsokYu5k2MfJ8A5oBkpWs'

    # https://developers.google.com/sheets/guides/values#appending_values
    values = {'values': test}
    result = service.spreadsheets().values().append(
        spreadsheetId=spreadsheetId, range=spreadsheetId,
        valueInputOption='RAW',
        body=values).execute()

if __name__ == '__main__':
    add_todo()

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

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